What is wrong here?


  • 0
    I

    I just check 32 bits of the integer and count. But the output is always 1 less than the Expected. Can anyone point where is wrong?

    public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count=0;
        while(n!=0){
            if(n%2==1){
                count++;
            }
            n>>>=1;
        }
        return count;
    }
    

    }


  • 0
    V

    I wrote the same code at first try, but always failed in this test case: 2147483648 (10000000000000000000000000000000), then I changed if(n%2==1){ count++; } to if((n & 1) == 1) count++;

    Then it works fine and accepted. Actually I'm not quite clear what's wrong with condition n % 2 ==1


  • 0
    I

    That is exactly where I got the same Wrong answer. Anyway thx!


  • 0
    L

    In java, 2147483648 is out of range, I can't even test this case in my own machine. It will show an error as "The literal 2147483648 of type int is out of range".


  • 0
    I

    yes, and I think that wrong answer is relevant to how they handle the INTEGER on this OJ. But can't figure out how. Actually I just checked, Java8 supports int to represent 32-bit unsigned integer, as the question required, of which Max is 4294967295, and they used it as a test case.


Log in to reply
 

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