Number of Even and Odd Bits - Problem

You are given a positive integer n.

Let even denote the number of even indices in the binary representation of n with value 1.

Let odd denote the number of odd indices in the binary representation of n with value 1.

Note: Bits are indexed from right to left in the binary representation of a number (0-indexed).

Return the array [even, odd].

Input & Output

Example 1 — Basic Case
$ Input: n = 17
Output: [2,0]
💡 Note: 17 in binary is 10001. Even indices (0,2,4): bits are 1,0,1 → count = 2. Odd indices (1,3): bits are 0,0 → count = 0.
Example 2 — Mixed Positions
$ Input: n = 2
Output: [0,1]
💡 Note: 2 in binary is 10. Even indices (0): bit is 0 → count = 0. Odd indices (1): bit is 1 → count = 1.
Example 3 — Larger Number
$ Input: n = 50
Output: [1,2]
💡 Note: 50 in binary is 110010. Even indices (0,2,4): bits are 0,0,1 → count = 1. Odd indices (1,3,5): bits are 1,0,1 → count = 2.

Constraints

  • 1 ≤ n ≤ 1000

Visualization

Tap to expand
Number of Even and Odd Bits: n = 17n = 17Convert to binary ↓10001pos 4pos 3pos 2pos 1pos 0Even positions (0,2,4): 2 onesOdd positions (1,3): 0 onesOutput: [2, 0]
Understanding the Visualization
1
Input
Integer n = 17
2
Binary Conversion
Convert to binary: 10001, index positions 0,1,2,3,4 from right
3
Count by Parity
Even positions (0,2,4): 2 ones, Odd positions (1,3): 0 ones
Key Takeaway
🎯 Key Insight: Use bit operations to check each position while tracking even/odd parity for optimal O(1) space solution
Asked in
Microsoft 15 Amazon 12
12.5K Views
Medium Frequency
~8 min Avg. Time
428 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen