191.|191. Number of 1 Bits
Problem
【191.|191. Number of 1 Bits】Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Example
Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011
Input: 128
Output: 1
Explanation: Integer 128 has binary representation 00000000000000000000000010000000
Code
static int var = [](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while(n!=0){
count += n % 2;
n = n/2;
}
return count;
}
};
Result
文章图片
191. Number of 1 Bits.png
推荐阅读
- LintCode|LintCode 545 [Top k Largest Number II]
- 136.|136. Single Number
- BitShares|BitShares 2.0、Steemit 2.0、BitUSD 2.0……BM在EOS上布局很大!
- 兼容性处理
- 基本包装类型
- ZOJ-3447---Doraemon's Number Game (贪心+大数)
- 数论|Codeforces 235E Number Challenge 莫比乌斯反演+数论
- FZU-2109 Mountain Number(数位dp)
- 力扣--Letter Combinations of a Phone Number
- 快乐数|快乐数 (lintcode:happy-number)