[Leetcode] #191 Number of 1 Bits
2017-02-16 15:21
405 查看
Discription:
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hammingweight).
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011,
so the function should return 3.
Solution:
#include <stdint.h>
int hammingWeight(uint32_t n) { //负数会溢出 int count = 0; while (n){ if (n & 1) count++; n = n >> 1; } return count; }
int hammingWeight(uint32_t n) { //循环次数变多 int count = 0; uint32_t a = 1; while (a){ if (n & a) count++; a <<= 1; } return count; }
int hammingWeight(uint32_t n) { //比较好的方法 int count = 0; while (n){ n = n&(n - 1); count++; } return count; }
GitHub-Leetcode:https://github.com/wenwu313/LeetCode
位运算相关参考:https://leetcode.com/problems/sum-of-two-integers/?tab=Solutions
相关文章推荐
- LeetCode Algorithms #191 <Number of 1 Bits>
- LeetCode191——Number of 1 Bits
- LeetCode 第 191 题 (Number of 1 Bits)
- [LeetCode][191][Number of 1 Bits]
- leetcode 191 Number of 1 Bits
- LeetCode 191,Number of 1 Bits
- 【LeetCode】190 & 191 - Reverse Bits & Number of 1 Bits
- LeetCode 第 191 题 (Number of 1 Bits)
- #leetcode#191 Number of 1 Bits n&n-1的用处
- LeetCode 191: Number of 1 Bits
- 【LEETCODE】191-Number of 1 Bits
- leetcode 191:Number of 1 Bits
- 【LeetCode-191】 Number of 1 Bits(C++)
- [Leetcode 191, Easy] Number of 1 Bits
- LeetCode 191 Number of 1 Bits
- [leetcode 191]Number of 1 Bits
- [leetcode 191]Number of 1 Bits
- LeetCode 191 Number of 1 Bits(1 比特的数字们)
- leetcode 191 Number of 1 Bits(难易度:Easy)
- LeetCode 191_Number of 1 Bits