[刷题] Bit - Leetcode - 191 Number of 1 Bits

Posted by 西维蜀黍的OJ Blog on 2019-07-28, Last Modified on 2019-07-28

Problem

Write a function that takes an unsigned integer and return the number of ‘1’ bits it has (also known as the Hamming weight).

Example 1:

Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Example 2:

Input: 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

Note:

  • Note that in some languages such as Java, there is no unsigned integer type. In this case, the input will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
  • In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 3 above the input represents the signed integer -3.

Follow up:

If this function is called many times, how would you optimize it?

Solution1

public int hammingWeight(int n) {
    if (n == 0)
        return 0;

    int flag = 1;
    int count = 0;
    for (int i = 0; i < 32; i++) {
        if ((n & flag) != 0)
            count++;

        flag = flag << 1;
    }
    return count;

}

Solution2

分析

每次对操作数 n 进行 n-1 的运算时,就会把操作数 n 的最右边的值为 1 的那个位(或者说值为 1 的最低位)的值置为 0,当然,进行这个减一操作时,这个位的低位可能会需要补 1。还是来举个例子:

比如操作数 n 为 1100,当执行 n-1运算时,就变成了1011,这里,从左往右数的第 2 个 1 变成了 0,而这个位置的低位的数字变成了 11。

我们将 n 和 n-1进行与运算,即1100 & 1011,结果为 1000。将1000重新赋值给 n。

再次进行 n 和 n-1进行与运算,即 1000 & 0111,结果为 0000。

规律:

我们发现执行 n-1运算时,被置为 0 的这个位的低位补 1 或者不需要补 1 的操作并不会影响与运算。

其次,原始操作数 n 中有多少个位为 1 ,就可以成功进行多少次与运算,直到 n 变成了0。

或者说,通过 n&(n-1)这个操作,可以起到消除最低位的那个1的作用。所以可以通过执行 n&(n-1) 操作来消除 n 末尾的 1 ,消除了多少次,就说明操作数 n 中有多少个 1 。

public int hammingWeight(int n) {
    if (n == 0)
        return 0;

    int count = 0;
    while (n != 0) {
        n = (n & (n - 1));
        count++;
    }
    return count;
}

Reference