Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Number of 1 Bits

Bit Manipulationeasy

Implement `hammingWeight(n)` returning the number of set bits (1s) in the binary representation of the non-negative integer `n`.

Sample tests

Input: hammingWeight(11)
Output: 3
Input: hammingWeight(128)
Output: 1

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Using signed shifts on large values; here values are small non-negatives.

Learning resources

  • MDN: Bitwise operators
Approach & explanation (try first)

Inspecting bits one at a time counts ones in O(number of bits) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.