LeetCode 191 Number of 1 Bits

Problem:

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

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

Summary:

求三十二位无符号数含1的位数。

Analysis:

1. 最简单的思路为将n移位直至n为0,每移位一次判断最低位是否为1。但若有1在最高位则需移位32次,效率太低。

 class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt = ;
while (n) {
cnt += n & ;
n = n >> ;
} return cnt;
}
};

2. 下面这种思路能够把移位的次数降低至与含1的位数相等,大大提高了效率。

举个栗子:若n = 1010010,则:

  1. n = 1010010  n - 1 = 1010001  n & (n - 1) = 1010000
  2. n = 1010000  n - 1 = 1001111  n & (n - 1) = 1000000
  3. n = 1000000  n - 1 = 0111111  n & (n - 1) = 0000000

可以看出,每进行一次n & (n - 1)操作,最低位上的1就会被消去。

 class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt = ;
while (n) {
n &= (n - );
cnt++;
} return cnt;
}
};
上一篇:Linux云计算运维-Redis


下一篇:[LeetCode] 191. Number of 1 Bits ☆(位 1 的个数)