オットセイの経営日誌

データサイエンス系ベンチャーを経営してます。経営のこと、趣味のことつぶやきます。

LeetCode / Number of 1 Bits

ビット表現祭りその2。

https://leetcode.com/problems/number-of-1-bits/

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.

解答・解説

解法1

下1桁が1であれば1を足すビット演算を32桁繰り返せば良いので、以下のように処理できます。

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        res = 0
        for _ in range(32):
            res += n&1
            n>>=1
        return res

時間計算量・空間計算量ともにO(1)なのでここで満足しても良いのですが、若干改善の余地があります。

解法2

32桁走査せずとも処理を完了できる可能性がある解法がこちら。

class Solution(object):
    def hammingWeight(self, n):
        res = 0
        while n != 0:
            res += 1
            n &= n-1
        return res

n&(n-1)のビット演算を行う手法です。
どういうことかというと、n = n&(n-1)のビット演算を行なうごとに'1'のbitの数が1つずつ消えていくので、nが0となるまでの処理の回数をカウントしてやれば良いんです。
具体例を示します。

n : 00000000000000000000000000001011

n : 00000000000000000000000000001011
n-1 : 00000000000000000000000000001010
n&(n-1): 00000000000000000000000000001010

n : 00000000000000000000000000001010
n-1 : 00000000000000000000000000001001
n&(n-1): 00000000000000000000000000001000

n : 00000000000000000000000000001000
n-1 : 00000000000000000000000000000111
n&(n-1): 00000000000000000000000000000000

という形ですね。