Number of Even and Odd Bits - Problem
You're given a positive integer n, and your task is to analyze its binary representation by counting specific bit positions.
In the binary representation of n, bits are indexed from right to left starting from index 0. Your goal is to count:
- even: The number of bits at even indices (0, 2, 4, ...) that have value 1
- odd: The number of bits at odd indices (1, 3, 5, ...) that have value 1
Example: For n = 17 (binary: 10001)
- Index 0 (rightmost): bit = 1 → even index with value 1
- Index 1: bit = 0 → odd index with value 0
- Index 2: bit = 0 → even index with value 0
- Index 3: bit = 0 → odd index with value 0
- Index 4: bit = 1 → even index with value 1
Result: [2, 0] (2 ones at even indices, 0 ones at odd indices)
Return an array [even, odd] containing these counts.
Input & Output
example_1.py — Basic Case
$
Input:
n = 17
›
Output:
[2, 0]
💡 Note:
17 in binary is 10001. Bit positions from right: 0(1), 1(0), 2(0), 3(0), 4(1). Even positions 0 and 4 have value 1, odd positions 1 and 3 have value 0.
example_2.py — Multiple Odd Bits
$
Input:
n = 2
›
Output:
[0, 1]
💡 Note:
2 in binary is 10. Bit positions from right: 0(0), 1(1). Even position 0 has value 0, odd position 1 has value 1.
example_3.py — Mixed Positions
$
Input:
n = 50
›
Output:
[1, 2]
💡 Note:
50 in binary is 110010. Bit positions from right: 0(0), 1(1), 2(0), 3(0), 4(1), 5(1). Even positions (0,2,4): one 1. Odd positions (1,3,5): two 1s.
Visualization
Tap to expand
Understanding the Visualization
1
Start from Right
Begin with position 0 (rightmost bit) and examine each bit
2
Check Bit Value
If the current bit is 1, determine if its position is even or odd
3
Update Counters
Increment even_count for positions 0,2,4... or odd_count for positions 1,3,5...
4
Move Left
Shift to the next bit position and repeat until all bits are processed
Key Takeaway
🎯 Key Insight: Use bitwise operations (n & 1 to check LSB, n >>= 1 to shift) to efficiently examine each bit while tracking position parity, avoiding string conversion overhead.
Time & Space Complexity
Time Complexity
O(log n)
We process each bit exactly once, and there are log₂(n) bits in the number
⚡ Linearithmic
Space Complexity
O(1)
Only using a few variables regardless of input size
✓ Linear Space
Constraints
- 1 ≤ n ≤ 1000
- n is a positive integer
- The binary representation will have at most 10 bits for the given range
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code