Number of Even and Odd Bits Problem
#2595
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2595.
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 that bits are indexed from right to left in the binary representation of a number.
Return the array [even, odd].
Example 1:
Input: n = 50
Output: [1,2]
Explanation:
The binary representation of 50 is 110010.
It contains 1 on indices 1, 4, and 5.
Example 2:
Input: n = 2
Output: [0,1]
Explanation:
The binary representation of 2 is 10.
It contains 1 only on index 1.
Constraints:
1 <= n <= 1000
Solution
Approach: Enumerate
Walk through the bits of n from the lowest to the highest, tracking whether the current index is even or odd. Each time the bit is 1, add one to the matching counter.
Complexity: time O(log n), space O(1).
class Solution:
def evenOddBit(self, n: int) -> List[int]:
ans = [0, 0]
i = 0
while n:
ans[i] += n & 1
i ^= 1
n >>= 1
return ans