Solution#1(2ms)
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1);
count++;
}
return count;
}
}
Solution#2
public class Solution {
// you need to treat n as an unsigned value
public static int hammingWeight(int n) {
int ones = 0;
while(n!=0) {
ones = ones + (n & 1);
n = n>>>1;
}
return ones;
}
}
Problem
1. >>>無符號位右移(補零),>>右移