Number of Even and Odd Bits
Here’s the Python code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| class Solution:
def evenOddBit(self, n: int) -> List[int]:
# Initialize counters for even and odd indices
even = 0
odd = 0
# Iterate over 32 bits
for i in range(32):
# Create a mask for the current bit
mask = 1 << i
# Use bitwise AND to check if the bit at the current position is 1
if n & mask:
# If the bit's position is odd, increment the odd counter
if i % 2:
odd += 1
# If the bit's position is even, increment the even counter
else:
even += 1
# Return the counts as a list
return [even, odd]
|
In this code, we initialize two counters, even and odd, to 0. We then create a loop to iterate over the 32 bits. For each bit, we create a mask using a bit shift, then use the bitwise AND operator to check if the bit at the corresponding position in the input number is 1. If the bit is 1, we check if the bit’s position is odd or even and increment the appropriate counter. Finally, we return the counters as a list.