本文完整拆解 LeetCode 191 Number of 1 Bits 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Number of 1 Bits 一次弄懂。
Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
Write a function that takes the binary representation of an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).
Note:
- Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer’s internal binary representation 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, the input represents the signed integer.
-3.
Example 1:
Input: n = 00000000000000000000000000001011 Output: 3 Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:
Input: n = 00000000000000000000000010000000 Output: 1 Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:
Input: n = 11111111111111111111111111111101 Output: 31 Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
Constraints:
- The input must be a binary string of length
32.
Follow up: If this function is called many times, how would you optimize it?
Python
class Solution {
public:
int hammingWeight(uint32_t n) {
int sum = 0, mask = 1;
for (int i = 0; i < 32; i++) {
if ((n & mask) != 0) sum++;
n >>= 1;
}
return sum;
}
};
Number of 1 Bits 解題思路
計算二進位中 1 的個數,逐位檢查要做滿 32 輪。更聰明的是 Brian Kernighan 技巧:n & (n-1) 這個運算會把最右邊的那個 1 變成 0,所以迴圈執行幾次就代表有幾個 1——有幾個 1 就跑幾輪,稀疏的數字會快得多。
Number of 1 Bits 演算法步驟
- 初始化計數器 count = 0。
- 當 n 不為 0 時進入迴圈。
- 執行 n = n & (n – 1),這會消去最右側的一個 1。
- count++,迴圈結束後回傳 count。
Number of 1 Bits 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(k) |
| 空間複雜度 | O(1) |
k 是 1 的個數,迴圈只跑 k 次,最壞 32 次,所以時間是 O(k),優於逐位檢查的固定 32 次。只用一個計數器,空間 O(1)。
Number of 1 Bits 的邊界情況與常見錯誤
- JavaScript 中輸入可能被當成有號數,必要時先用 >>> 0 轉無號。
- n 為 0 時迴圈不執行,直接回傳 0。
- n & (n-1) 的原理是借位會把最右邊的 1 之後全部翻轉,理解它才不會寫成 n & n-1 的優先序錯誤。
- 若要頻繁呼叫,可用查表法預先算好每個位元組的 1 數量。
Number of 1 Bits 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 逐位右移檢查最低位 | O(32) | O(1) | 固定 32 輪,稀疏時浪費 |
| 查表法(預算每個位元組) | O(1) | O(256) | 需要前置表格 |
| Brian Kernighan 技巧 | O(k) | O(1) | 本文採用 |
