问题描述:
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
简述:
给一个无符号整型数,求它的二进制形式中1的数量。
解题思路:
思路1:
通过位操作解题。将n与1进行位与操作可以判断n的最后一位二进制位是否为1,不断将n与1进行位与操作,统计1的数量。
int hammingWeight(uint32_t n) {
int f = 1;
int num = 0;
while(n) {
if(n&f) {
++num;
}
n = n>>1;
}
return num;
}
思路2:
观察以下几组数据:
n: 1101 n-1: 1100 n&(n-1): 1100
n: 1110 n-1: 1101 n&(n-1): 1100
n: 1100 n-1: 1011 n&(n-1): 1000
不难发现,利用n&(n-1)可以将n二进制形式中最末尾的1置0。
因此,不断的进行n&(n-1)的操作,直到n为0,统计操作次数即为1的个数。
int hammingWeight(uint32_t n) {
int num = 0;
while(n) {
++num;
n = n&(n-1);
}
return num;
}