ntree.aiNumber of 1 Bits
Solutions
1. Brute Force
O(logn) time | O(1) space
Intuition
We can find the bits of a number the same way we convert it to binary by hand.
The remainder of dividing it by 2 is its last bit, and dividing it by 2 drops that bit.
So we can repeat the division until the number becomes zero and sum the remainders.
Algorithm
- Create a
countvariable with initial value0. - While
nis greater than0:- Add the remainder of
ndivided by2tocount. - Divide
nby2, dropping the remainder.
- Add the remainder of
- Return
count.
11
1
0
1
1
11 % 2 = 1, count = 1, 11 / 2 = 5
1 / 5
11
1
0
1
1
Code
Code
def hammingWeight(n: int) -> int:
count = 0
while n:
count += n % 2
n //= 2
return count/**
* @param {number} n
* @returns {number}
*/
var hammingWeight = function (n) {
let count = 0
while (n !== 0) {
count += n % 2
n = Math.floor(n / 2)
}
return count
}class Solution {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count += n % 2;
n /= 2;
}
return count;
}
}2. Clear the Last 1 Bit
O(k) time | O(1) space, for k 1 bits
Intuition
n & (n - 1) operation removes the last 1 bit of n.
This happens because n - 1 turns the last 1 bit into 0 and every 0 bit after it into 1.
So we can repeat this operation until n is zero where the number of iterations is the number of 1 bits.
Algorithm
- Create a
countvariable with initial value0. - While
nis greater than0, replacenwithn & (n - 1)and increasecountby one. - Return
count.
1
0
1
1
&
10
1
0
1
0
1
0
1
0
11 & 10 = 10, count = 1
1 / 4
Code
Code
def hammingWeight(n: int) -> int:
count = 0
while n:
n &= n - 1
count += 1
return count/**
* @param {number} n
* @returns {number}
*/
var hammingWeight = function (n) {
let count = 0
while (n !== 0) {
n &= n - 1
count++
}
return count
}class Solution {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n &= n - 1;
count++;
}
return count;
}
}def hammingWeight(n: int) -> int: pass Press Visualise to step through your code.