一道題 1

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.

solution1

常規解法: 用模板,然後右移一位。

int hammingWeight(uint32_t n) {
     int count = 0;
     for(int i = 0; i < 32; i++)
 {
     if( n & 0x01 )
     {
         count++;
     }
     n = n >> 1;
 }
 return count;
 }

可以優化成這樣 count += n&1;

solution2

對數據取餘,也就是檢測最後一位是否爲1,然後右移一位。

int hammingWeight(uint32_t n) {
int result = 0;
for(n) {
    result += n%2;
    n /= 2;
}
}

solution3

n&n-1將最後一位不爲0的位置0,直到n值爲0.

int hammingWeight(uint32_t n) {
int ret = 0;
while(n)
{
    n&=n-1;
    ++ret;
}
return ret;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章