Number of 1 Bits
2015-03-12 07:40
99 查看
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming
weight).
For example, the 32-bit integer ’11' has binary representation
so the function should return 3.
思路有两种:
第一种:
将n二进制化,在二进制化的过程中统计1的个数
java中没有无符号整数的表示,所以不是很容易,int 的范围是-2147483648 ~ 2147483647
第二种:
利用按位与,统计1的个数
Runtime: 220
ms
weight).
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011,
so the function should return 3.
思路有两种:
第一种:
将n二进制化,在二进制化的过程中统计1的个数
java中没有无符号整数的表示,所以不是很容易,int 的范围是-2147483648 ~ 2147483647
第二种:
利用按位与,统计1的个数
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int count = 0; int tmp = 1; int i = 0 ; while(i < 32){ if((n & tmp) != 0 ){ count ++; } tmp = tmp << 1; i++; } return count; } }注意:& 的优先级低于 != ,所以n&tmp要加括号
Runtime: 220
ms
相关文章推荐
- Number of 1 Bits
- LeetCode191——Number of 1 Bits
- Number of 1 Bits
- [Leetcode] Number of 1 Bits
- Number of 1 Bits
- 【leetcode】Number of 1 Bits
- Number of 1 Bits——LeetCode
- LeetCodeOJ_191_Number of 1 Bits_e
- #191 Number of 1 Bits
- leetcode 191: Number of 1 Bits
- LeetCode--Number of 1 Bits
- Number of 1 BitsWrite a function that takes an unsigned integer and returns the number of ’1' bits i
- Leetcode—— Number of 1 Bits——最简单的一题
- LeetCode 191 Number of 1 Bits
- (LeetCode 191) Number of 1 Bits
- leetcode:bits:Number of 1 Bits(191)
- LeetCode 191 Number of 1 Bits (位运算)
- Number of 1 Bits问题及解法
- leetCode #191 number of 1 bits
- [LeetCode刷题记录]190-191 Number of 1 Bits & Reverse Bits