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.
class Solution { public: int hammingWeight(uint32_t n) { int k = 0; while(n) { k += (n & 0x1) > 0 ? 1 : 0; //(n % 2) > 0 ? 1 : 0; n >>= 1; //n /= 2; } return k; } };
这是比较容易想到的解决办法,每次判断最后一位是否是1。但是这样32位的数最坏的情况要比较32次。有没有更简单的方法呢?
下面这种方法更为简单。假设n=
1111000111000 那 n-1 = 1111000110111,
(n-1) & n = 1111000110000,刚好把最后一个1给干掉了。也就是说,
(n-1)&n 刚好会从最后一位开始,每次会干掉一个1.这样速度就比上面哪种方法快了。有几个1,就执行几次。(学渣表示震惊!= =)
class Solution { public: int hammingWeight(uint32_t n) { int k = 0; while(n != 0) { n = n & (n-1); k++; } return k; } };
时间: 2024-10-13 06:36:18