題目描述:
Write a function that takes an unsigned integer and returns the number of '1'?bits it has (also known as the?Hamming weight).
Example 1:
Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011
Example 2:
Input: 128
Output: 1
Explanation: Integer 128 has binary representation 00000000000000000000000010000000
?
要完成的函數:
int hammingWeight(uint32_t n)?
?
說明:
1、這道題目給定一個數n,要求轉換為二進制之后,數一下有多少個1,輸出1的個數。
2、明白題意,這道題用位操作完成,十分容易。
代碼如下:(附詳解)
int hammingWeight(uint32_t n) {int res=0;for(int i=0;i<32;i++){res+=(n&1);//取出最后一位,如果是1那么加上去,如果是0加上去也一點影響都沒有,避開了條件判斷n>>=1;//n右移一位}return res;}
上述代碼實測4ms,beats 100% of cpp submissions。