191. Number of 1 Bits
寫一個函數,該函數接收一個正整數的二進制表示並返回其中的 置位 數量(也稱為漢明重量)。
範例:
輸入:n = 11
輸出:3
解釋:
輸入的二進制字符串 1011 總共有三個置位。
輸入:n = 11
輸出:3
解釋:
輸入的二進制字符串 1011 總共有三個置位。
Python
class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n:
count += n & 1 # Add the least significant bit to the count
n >>= 1 # Right shift n to process the next bit
return count
16.43MB, 40ms
C++
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while (n) {
count += n & 1; // Add the least significant bit to the count
n >>= 1; // Right shift n to process the next bit
}
return count;
}
};
7.95MB, 0ms
Javascript
/**
* @param {number} n
* @return {number}
*/
var hammingWeight = function(n) {
let count = 0;
while (n !== 0) {
count += n & 1; // Add the least significant bit to the count
n >>>= 1; // Right shift n to process the next bit, using unsigned shift to avoid negative numbers
}
return count;
};
49.47MB, 49ms