剑指 Offer 15. 二进制中1的个数

剑指 Offer 15. 二进制中1的个数_第1张图片
思路:位运算
注意 >> 和 >>>的区别:
  >>表示右移,如果该数为正,则高位补0,若为负数,则高位补1;
  >>>表示无符号右移,也叫逻辑右移,即若该数为正,则高位补0,而若该数为负数,则右移后高位同样补0。

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

你可能感兴趣的:(剑指offer)