Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).ui
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.this
Credits:
Special thanks to @ts for adding this problem and creating all test cases.code
第一反應是直接用x & (x-1)的循環到x=0來算。第二反應是分字節的查表法。
代碼之美的第10章「尋找快速的種羣計數」有更深刻的講解,用了其中的最優的方法。ci
按位計算,第一次是奇偶位相加放在每兩位的地方。而後每4位的兩位兩位相加,放在每4位的結果上。知道32位的每16位相加。因爲最多隻有32個1,也就是隻有低位的5bit有效,後面的八、16的不用再移位計算,溢出的高位部分無所謂,最後用&清0便可。get
class Solution { public: int hammingWeight(uint32_t n) { n = n - ((n>>1) & 0x55555555); n = (n & 0x33333333) + ((n>>2) & 0x33333333); n = (n + (n>>4)) & 0x0f0f0f0f; n = n + (n>>8); n = n + (n>>16); return n & 0x3f; } };