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 INPUT n = 17 Binary: 17 in base 2 1 0 0 0 1 Bit Indices (right to left): 1 idx 4 (even) 0 idx 3 (odd) 0 idx 2 (even) 0 idx 1 (odd) 1 idx 0 (even) = bit is 1 = bit is 0 ALGORITHM STEPS 1 Initialize counters even = 0, odd = 0 2 Loop through bits while n > 0: 3 Check each bit bit = n & 1 if bit==1: count it 4 Shift and toggle n = n >> 1 toggle even/odd index Iteration Trace: idx=0: bit=1 ---> even++ idx=1: bit=0 ---> skip idx=2: bit=0 ---> skip idx=3: bit=0 ---> skip idx=4: bit=1 ---> even++ FINAL RESULT Counting Summary: Even Index 1-bits idx 0 and idx 4 Count: 2 Odd Index 1-bits None found Count: 0 Output Array: [2, 0] [even, odd] OK - Verified Key Insight: Use bit manipulation (n & 1) to extract the rightmost bit, then right-shift (n >> 1) to process the next bit. Track the current index parity - indices alternate between even (0,2,4...) and odd (1,3,5...). Time Complexity: O(log n) | Space Complexity: O(1) TutorialsPoint - Number of Even and Odd Bits | Optimal 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