Number of 1 Bits

Easy#191bit by bit

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: 13 is 1101, so 3.
constraints
  • 1 ≤ n ≤ 2³¹ − 1
our 16 tests keep to them
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

16 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more bit manipulation problems

Pattern “Bit manipulation” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.