[LeetCode]Number of 1 Bits
2016-12-13 22:19
155 查看
Question
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
00000000000000000000000000001011, so the function should return 3.
本题难度Easy。有2种算法分别是: 移位法 和 减一相与法
1、移位法
复杂度
时间 O(N) 空间 O(1)思路
通过与运算符判断最低位/最高位是否是1,然后再右移/左移。重复此步骤直到原数归零。代码
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { //require int ans=0; //invariant for(int i=0;i<32;i++){ if((n&1)==1)ans++; n>>=1; } //ensure return ans; } }
注意
这道题说的是把n当作 unsigned integer,但是
n仍然是signed integer。第9行写为
>>>,循环条件可以写成
while(n!=0):
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int mark = 0b1, count = 0; while(n != 0b0){ if((n & mark)==0b1){ count++; } n >>>= 1; } return count; } }
但是第9行写为
>>,循环条件就不可是
while(n!=0)。为简化假设
n只有4位,第1位为符号位,令
n=-3,二进制就是
1101,那么进行
n>>=1后得到的二进制结果为
1110(符号位右移了,但是符号位不会变成0),所以要注意。
参见:Java整数占几个字节,以及负数的二进制表示方法,以及Java的逻辑运算符>>和>>>的区别
2、减一相与法
复杂度
时间 O(N) 空间 O(1)思路
该方法又叫Brian Kernighan方法。当n不为0时,
n = n & (n - 1);。因为每次减一如果最右边有1那么消除右边的1,所以消去几次就有几个1。
比如:
011,减去1得010,相与得010,消去了最右边的1
110,减去1得101,相与得100,消去了最右边的1
代码
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int count = 0; while(n != 0){ n = n & (n - 1); count++; } return count; } }
参考
[Leetcode] Number of 1 Bits 一的位数相关文章推荐
- LeetCode - Number of 1 Bits
- [LeetCode] Number of 1 Bits 位1的个数
- Leetcode NO.191 Number of 1 Bits
- leetcode笔记:Number of 1 Bits
- leetcode number of 1 bits
- 2016.5.15——leetcode:Number of 1 Bits ,
- 【Leetcode】Number of 1 Bits(easy)
- leetcode:Number of 1 Bits
- LeetCode: Number of 1 Bits
- LEETCODE-Number of 1 Bits
- 【leetcode】Number of 1 Bits (easy)
- [Leetcode] Number of 1 Bits
- LeetCode Algorithms #191 <Number of 1 Bits>
- LeetCode(191)Number of 1 Bits
- LeetCode:Number of 1 Bits
- leetcode:Number Of 1 Bits
- leetcode_Number of 1 Bits
- Number of 1 Bits--LeetCode
- LeetCode Number of 1 Bits
- (java)leetcode Number of 1 Bits