public class Solution {
// you need to treat n as an unsigned value
public static int hammingWeight(int n) {
int count=0;
if(n<0){
count++;
}
while(n!=0){
if((n&1) == 1){
count++;
}
n>>=1;
if(n == 1){
count++;
break;
}
}
return count;
}
}
Why I cannot get through this situation：2^32 ?

@ermao in java you need to use this operator ">>>" instead of ">>" on unsigned integers. I know its annoying..

@alan28 Thank you! You are correct!
Use ">>>" to replace ">>", and remove the "n<0" case, then I passed.
Here's the code.
public class Solution { // you need to treat n as an unsigned value public static int hammingWeight(int n) { int count=0; while(n!=0){ if((n&1) == 1){ count++; } n >>>= 1; if(n == 1){ count++; break; } } return count; } }