<aside>
💡 AND (&
) the whole number to get last bit. Then do UNSIGNED RIGHT SHIFT (>>>
) and repeat until number ends (becomes zero).
</aside>
https://leetcode.com/problems/number-of-1-bits/
function hammingWeight(number) {
let count = 0;
function scan(current) {
if (current == 0) {
return;
}
if (current & 1 == 1) {
count++;
}
return scan(current >>> 1);
}
scan(number);
return count;
}
<aside> 💡 Do “Number of 1 bits” for every number in a range.
</aside>
https://leetcode.com/problems/counting-bits/
function countBits(number) {
const result = [];
function getCount(number, count = 0) {
if (number === 0) {
return count;
}
if (current & 1 ===1) {
count++;
}
return getCount(number >>> 1, count);
}
for (let i = 0; i <= number; i++) {
result.push(getCount(i));
}
return result;
}