JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).

Example 1:

Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011

Example 2:

Input: 128
Output: 1
Explanation: Integer 128 has binary representation 00000000000000000000000010000000

Code

class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        // 不能用n <= 0, return 0
        // 因为这样会把n当做有符号数字,负数就直接返回0了
        int res = 0;
        for(int i = 0; i < 32; i++){
            res += n & 1;
            n >>= 1;
        }

        return res;
    }
}
class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int res = 0;
        while(n != 0){
            // 消去n末尾的1
            n &= (n - 1);
            res++;
        }

        return res;
    }
}