[LeetCode] 191. Number of 1 Bits

linspiration發表於2019-01-19

Problem

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

Example

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

Solution

//#1
public class Solution {
    /**
     * @param n: an unsigned integer
     * @return: the number of ’1` bits
     */
    public int hammingWeight(int n) {
        // write your code here
        int count = 0;
        while (n != 0) {
            n &= n-1;
            count++;
        }
        return count;
    }
}


//#2
public class Solution {
    /**
     * @param n: an unsigned integer
     * @return: the number of ’1` bits
     */
    public int hammingWeight(int n) {
        // write your code here
        int count = 0;
        while (n != 0) {
            count += (n&1);
            n = n>>>1;  //unsigned bit right shift
        }
        return count;
    }
}


//#3
public class Solution {
    /**
     * @param n: an unsigned integer
     * @return: the number of ’1` bits
     */
    public int hammingWeight(int n) {
        // write your code here
        int count = 0;
        for (int i = 0; i < 32; i++) {
            if ((n & (1<<i)) != 0) count++;
        }
        return count;
    }
}

相關文章