Problem Description
Given a positive integer n, return an array containing two numbers: the count of ones at even indices and the count of ones at odd indices in the binary representation of n. The binary bits are indexed from right to left, starting at index 0.
Key Insights
- The binary representation must be processed starting from the least significant bit (rightmost bit) since indices are defined from right to left.
- For each bit, if it equals 1, determine whether its index is even or odd and increment the respective counter.
- Bit manipulation (using bitwise AND and right-shift operations) provides an efficient way to check each bit without converting the number to a string.
Space and Time Complexity
Time Complexity: O(log n) - The algorithm iterates through each bit of n. Space Complexity: O(1) - Only constant extra space is used for counters and index.
Solution
The solution works by initializing two counters, even and odd, to 0. Starting with index 0 and the given number n, the algorithm checks the least significant bit of n using a bitwise AND with 1. If the result is 1, it increments the even counter if the current index is even, or the odd counter if the index is odd. Then, the algorithm right-shifts n by one (dividing by 2) and increments the index. This process continues until n becomes 0. The result is returned as a two-element array [even, odd].