int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1); // clears the lowest set bit
count++;
}
return count;
}
class Solution {
public:
int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1);
count++;
}
return count;
}
};
package bitmanipulation
func hammingWeight(n int) int {
count := 0
for n != 0 {
n = n & (n - 1) // clears the lowest set bit
count++
}
return count
}
class Solution {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1); // clears the lowest set bit
count++;
}
return count;
}
}
/**
* @param {number} n
* @return {number}
*/
var hammingWeight = function (n) {
let count = 0;
while (n !== 0) {
n = n & (n - 1); // clears the lowest set bit
count++;
}
return count;
};
class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n != 0:
n = n & (n - 1) # clears the lowest set bit
count += 1
return count
impl Solution {
pub fn hamming_weight(mut n: i32) -> i32 {
let mut count = 0;
while n != 0 {
n = n & (n - 1); // clears the lowest set bit
count += 1;
}
count
}
}