題:
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.
也是就輸入一個無符號整數,對其二進制裏面的1進行計數。
solution:
這道題主要一個陷阱就是,題目要求計算的是該整數無符號二進制中的1的個數,但是整數實際上在計算機中是按照有符號二進制補碼存儲會有一位符號位,所以當輸入爲
我們只需要把輸入的32位無符號整數用long類型存儲,這樣可以避免數據位被轉化成符號位。
class Solution {
public:
int hammingWeight(uint32_t n) {
long m = n;
int count=0;
int i=0;
while((m>>i)>0)
{if((m>>i)&1==1)count++;i++;}
return count;
}
};