Why my solution is wrong?


  • 1
    X
    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/=2;
        }
        return count;
    }
    

    }


    Input:
    2147483648 (10000000000000000000000000000000)
    Output:
    0
    Expected:
    1


  • 2
    S

    With "2147483648" as input, Java really treats the integer as a negative number, note the range of Integer is [-2147483648, 2147483647]. So, it doesn't go into the while loop as n<0. Change to n!=0 and world is all good again.


Log in to reply
 

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