2595. Number of Even and Odd Bits
Description
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
Solutions
Solution 1: Enumerate
According to the problem description, enumerate the binary representation of \(n\) from the low bit to the high bit. If the bit is \(1\), add \(1\) to the corresponding counter according to whether the index of the bit is odd or even.
The time complexity is \(O(\log n)\) and the space complexity is \(O(1)\). Where \(n\) is the given integer.
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Solution 2: Bit Manipulation
We can define a mask \(\textit{mask} = \text{0x5555}\), which is represented in binary as \(\text{0101 0101 0101 0101}_2\). Then, performing a bitwise AND operation between \(n\) and \(\textit{mask}\) will give us the bits at even indices in the binary representation of \(n\). Performing a bitwise AND operation between \(n\) and the complement of \(\textit{mask}\) will give us the bits at odd indices in the binary representation of \(n\). We can count the number of 1s in these two results.
The time complexity is \(O(1)\), and the space complexity is \(O(1)\). Here, \(n\) is the given integer.
1 2 3 4 5 6 |
|
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 |
|