Number of 1 Bits

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.

 

思路比较简单,直接贴代码:

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int re = 0;
        int bit = 0;
        for(int i=0;i<32;i++) {
            bit = n&1;
            if(bit==1) re++;
            n>>=1;
        }
        return re;
    }
}

当然这样写也可以:

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        return Integer.bitCount(n);
    }
}

 

posted @ 2015-03-10 13:30  mrpod2g  阅读(124)  评论(0编辑  收藏  举报