LeetCode Problem Number: 2595

Number of Even and Odd Bits

Solve on LeetCode

Problem 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:

Input: n = 17
Output: [2, 0]
Explanation: The binary representation of 17 is 10001.
The bits at even indices are [1, 0, 0, 1] (count: 2).
The bits at odd indices are [0, 0] (count: 0).

Solution Code


class Solution {
public:

    bool evenOrOdd(int n){
        if(n & 1) return false;
        return true;
    }
    vector evenOddBit(int n) {
        int odd = 0, even = 0;
        vector ans;
        long long int pos = 0;
        long long int lb;
        while(n > 0){
            lb = n & 1;
            if(lb){
                if(evenOrOdd(pos)) even++;
                else odd++;
            }
            pos++;
            n >>= 1;
        }
        ans.push_back(even);
        ans.push_back(odd);
        return ans;
    }
};
                    

Solution Explanation

The problem requires counting the number of bits set to 1 at even and odd positions in the binary representation of a given number. The solution follows these steps:

  • Iterate Over Bits: Use bitwise operations to iterate through each bit of the number.
  • Check Bit Position: Determine if the bit is at an even or odd position using bitwise operations.
  • Count Bits: Count the number of 1s at even and odd positions separately.
  • Return Result: Return the counts in an array where the first element is the count of even bits and the second element is the count of odd bits.