Skip to the editor
JSGroundwork
JSGroundwork handwritten · web dev
←Back to Bit manipulation

Ready to read

JSJavaScript⑂Git◎Interview prepΣDSA in JSSDSystem Design
More topics15›
</>HTML{ }CSS⚛ReactNNext.jsNeNest.jsTSTypeScriptNoNode.js🐳DockerDBSQL & Databases✓Testing🔒Web Security☁Cloud & DevOps◈GraphQL◆Redis☸Kubernetes
☰‹›
Description
All topics›JavaScript›Bit manipulation

Number of 1 Bits

beginnerlayer I11 · Bit manipulation5 tests

Given an unsigned 32-bit integer n, return how many bits in its binary representation are set to 1 (its Hamming weight).

  • n may be as large as 4294967295, so the top bit can be set
  • The JS trap: every bitwise operator coerces its operands to a signed 32-bit integer. Once bit 31 is set, n >> 1 keeps shifting a 1 in from the left and your loop never terminates.
  • The fix is the unsigned right shift: normalise with n >>> 0 and shift with >>>, never >>

Stuck?

All exercisesPlayground
1234567891011121314
loading the editor…

Nothing yet — hit Run and whatever you log shows up here.

Submit to see how you did.

⌘/Ctrl + Enter run⌘/Ctrl + S save⌘/Ctrl + / comment⌘/Ctrl + F find/replace⌘/Ctrl + D select next matchAlt + click multi-cursorTab indent · ⇧Tab outdentEsc leave fullscreen