【Leetcode】python - [191] Number of 1 Bits 個人解法筆記

題目出處

191. Number of 1 Bits

難度

easy

個人範例程式碼

class Solution:
    def hammingWeight(self, n: int) -> int:

        # 7 (10) = 111 (2)
        # 4 (10) = 100 (2)
        # 3 (10) = 011 (2)

        cnt = 0
        while(n != 0):
            cnt += (n & 1) # and first bit
            n = n >> 1 # (// 2)
        return cnt 

算法說明

簡單的位元運算題目,
我們可以先觀察「 10進位 (10) 與 2進位 (2) 」的變化,

7 (10) = 111 (2)

4 (10) = 100(2)

3 (10) = 11(2)

我們提取第一個位元 (最右側位元) 的方式是 (原數字 & 1),
並一路往右 » 1,直到原值只剩下 0。

input handling

x

Boundary conditions

用 while 至 0 來控制範圍。

Reference