Number of 1 Bits问题及解法
2017-03-27 10:26
471 查看
问题描述:
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
示例:
the 32-bit integer ’11' has binary representation
问题分析:
可根据向右移位与1按位与操作,可得‘1’的数目。
还有一种更高效的方式 : n = n &( n -1 )
过程详见代码:
按位与
class Solution {
public:
int hammingWeight(uint32_t n) {
uint32_t flag = 1;
int res = 0;
while(n)
{
res += (n & flag);
n = n >> 1;
}
return res;
}
};
更高效方式:
int hammingWeight(uint32_t n) {
int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
示例:
the 32-bit integer ’11' has binary representation
00000000000000000000000000001011, so the function should return 3.
问题分析:
可根据向右移位与1按位与操作,可得‘1’的数目。
还有一种更高效的方式 : n = n &( n -1 )
过程详见代码:
按位与
class Solution {
public:
int hammingWeight(uint32_t n) {
uint32_t flag = 1;
int res = 0;
while(n)
{
res += (n & flag);
n = n >> 1;
}
return res;
}
};
更高效方式:
int hammingWeight(uint32_t n) {
int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
相关文章推荐
- leetcode [Number of 1 Bits]//待整理多种解法
- Number of Islands问题及解法
- [LeetCode] Number of 1 Bits & Reverse Integer - 整数问题系列
- Binary Number with Alternating Bits问题及解法
- Number of Segments in a String问题及解法
- Reverse Bits问题及解法
- 过河问题的图论解法
- 同一问题的两种不同解法 : MFC8.0 与 C++ 标准库
- Hanoi(汉诺)问题的非递归解法
- 背包问题 顺推解法
- 连续自然数之和问题(多种解法)
- 一个问题的多种解法:
- 中国剩余定理:一类初数题的通用解法(除数,余数问题)(转载)
- JAVA中文问题及最优解法
- "100 个台阶"问题的 4 种解法
- SetBitmapBits问题
- josephus问题的解法
- 皇后问题的一个解法
- 寻找必败态——一类博弈问题的快速解法
- 约瑟夫环问题单循环链表解法