LeetCode刷题实战191:位1的个数
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
题意
示例
示例 1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
示例 2:
输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
示例 3:
输入:11111111111111111111111111111101
输出:31
解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
解题
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
for(int i = 0; i < 32; i++) {
if(n & 1 == 1) {
count += 1;
}
n = n >> 1;
}
return count;
}
};
评论