NOTE
Number of 1 Bits
Count the number of 1 bits in a 32-bit binary representation by shifting through each bit.
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
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub