NOTE
Number of 1 Bits
Given an integer, output the number of 1s in its 32-bit binary representation. Negative numbers are represented using two's complement.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
Given an integer, output the number of 1s in its 32-bit binary representation. Negative numbers are represented using two’s complement.
2. Approach
- Bit shifting
3. Implementation
// Time: O(1)
// Space: O(1)
func NumberOf1(n int) int {
count := 0
bit := 1
for i := 0; i < 32; i++ {
if n&bit > 0 {
count++
}
bit = bit << 1
}
return count
}
4. References
Drag to pan, scroll to zoom, and click a node to expand or collapse it. Large maps start with deeper levels collapsed; click nodes to expand them.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub