Number of 1 Bits
You get a positive integer. Count how many of its bits are 1. Our example: n = 90 = 1011010 — the answer is 4.
- input
n: a positive integer.- returns
- How many ones its binary form has:
13is1101, so3. - constraints
- 1 ≤ n ≤ 2³¹ − 1
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* @param {number} n
* @return {number}
*/
function hammingWeight(n) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more bit manipulation problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.