首页 > 代码库 > 191. Number of 1 Bits

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 theHamming weight).

For example, the 32-bit integer ’11‘ has binary representation 00000000000000000000000000001011, so the function should return 3.

Solution 1:

看起来是一道非常简单的题目,但是自己在做的时候却漏洞百出。

思路:存一个count,每次将n向右移一位,检查最后一位是否为1,是1就将count加一。

注意shift number不会改变number本身,要赋值给number本身才可以。

注意overflow的情况,所以不能把n放在while的条件里面做判断。

Bit Manipulation Ref:

http://www.tutorialspoint.com/java/java_basic_operators.htm

 

public class Solution {    // you need to treat n as an unsigned value    public int hammingWeight(int n) {        int count=31;        int res=0;        while(count>=0)        {            if((n&1)!=0)            {                res++;            }            n=n>>>1;            count--;        }        return res;    }}

Solution2:

看了discussion,居然有种作弊的方法!!!

return Integer.bitCount(n);

Solution3: 

public class Solution {    // you need to treat n as an unsigned value    public int hammingWeight(int n) {        int count = 0;        int mask = 1;        int i = 0;        while(i < 32) {            if ((n&mask) != 0) {                count++;            }            mask <<= 1;            i++;        }        return count;    }}

思路跟1是一样的,但是这种是每次移i次,。移位的简写方式:<<=,>>=. >>>三个箭头是fill left by 0.

Solution 4: 

public class Solution {    // you need to treat n as an unsigned value    public int hammingWeight(int n) {        int count = 0;                for (count = 0; n != 0; count++) {            n &= n - 1;     // clear the least significant bit set        }                return count;    }}

这解法太巧了!把最右边的1清零,有多少1就清零多少次。然后累加次数

111000 & 110111=110000

110000 & 101111 =100000

100000 & 011111 =000000

191. Number of 1 Bits