Why n%2 == 1 can't work?

  • 0

    int count = 0;
    while(n != 0){
    if(n%2 == 1) count++;

            n>>>= 1;
        return count;

  • 0

    Hi, because when n<0 and when the first time iteration start, n%2 will be -1 instead of 1. So if you change your code to if(n%2==1||n%2==-1) it will work although (n%2==-1) will only be triggered in the first iteration. Hope this will help

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.