EASY NC#145 Blind #12 Bit Manipulation

191. Number of 1 Bits

๐Ÿ“– Problem

Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ Use bitwise AND with 1 to check if last bit is set
  • โ†’ Right shift n to examine each bit
  • โ†’ Loop until n becomes 0
  • โ†’ Time: O(log n) where n is the value (max 32 iterations for 32-bit), Space: O(1)
  • โ†’ in popcount

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse bitwise AND with 1 to check if last bit is set
  • โ€ขRight shift n to examine each bit
  • โ€ขLoop until n becomes 0

Common Pitfalls

  • โ€ขTime: O(log n) where n is the value (max 32 iterations for 32-bit), Space: O(1)
  • โ€ขin popcount

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
hammingWeight(11);
Expected:
3
Test Case 2
Not run
Input:
hammingWeight(128);
Expected:
1
Test Case 3
Not run
Input:
hammingWeight(0);
Expected:
0

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit