【leetcode】191. Number of 1 Bits

版权声明:来自 T2777 ,请访问 https://blog.csdn.net/T2777 一起交流进步吧 https://blog.csdn.net/T2777/article/details/87544304

问题描述:

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

Example 1:

Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Example 2:

Input: 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

代码为(uint32_t 是无符号32位整型):

class Solution {
public:
    int hammingWeight(uint32_t n) {
      int res = 0;
        while(n > 0)
        {
            //1000 & 0111 = 0000,所以有 1 个 1
            //1001 & 1000 = 1000,所以有 2 个 1
            //1010 & 1001 = 1000,所以有 2 个 1
            // 使得 n 的最低位的 1 变为 0
            n = (n & (n - 1));
            res++;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/T2777/article/details/87544304
今日推荐