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
๐ค Output