191. Number of 1 Bits

问题:

给定32位无符号整型数 uint32_t n

求该数中1出现的次数。

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

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

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

Constraints:
The input must be a binary string of length 32.

  

解法:bit 运算。

  • n&(n-1):
    • 去掉末尾 1 位。

例如:0110->0100

本题,则对n不断去除末尾 1.

同时计算去除次数,最后到n==0。

说明,去除完所有 1.

返回次数即为 n中含有 1 的次数。

代码参考:

 1 class Solution {
 2 public:
 3     int hammingWeight(uint32_t n) {
 4         int res = 0;
 5         while(n) {
 6             n &= (n-1);
 7             res++;
 8         }
 9         return res;
10     }
11 };
原文地址:https://www.cnblogs.com/habibah-chang/p/14569264.html