Leetcode 2595. Number of Even and Odd Bits
You are given a positive integer n
. Your task is to determine the number of bits set to 1 at even positions and the number of bits set to 1 at odd positions in the binary representation of n
. Position indexes are 0-based from the least significant bit (rightmost bit).
Return an array where the first element is the number of 1 bits at even positions and the second element is the number of 1 bits at odd positions.
n
is a positive integer.To solve this problem, we will:
n
using bitwise operations:
#include <vector>
std::vector<int> evenOddBitCounts(int n) {
int evenCount = 0, oddCount = 0;
int position = 0;
while (n > 0) {
if ((n & 1) == 1) { // Check if the least significant bit is set
if (position % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
n = n >> 1; // Right shift `n` to process the next bit
position++;
}
return {evenCount, oddCount};
}
The time complexity of this solution is O(log n) where n
is the input number, because we are processing each bit of the number, and there are log(n) bits in the binary representation of n.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?