2595. Number of Even and Odd Bits LeetCode Solution

In this guide, you will get 2595. Number of Even and Odd Bits LeetCode Solution with the best time and space complexity. The solution to Number of Even and Odd Bits problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Number of Even and Odd Bits solution in C++
  4. Number of Even and Odd Bits solution in Java
  5. Number of Even and Odd Bits solution in Python
  6. Additional Resources
2595. Number of Even and Odd Bits LeetCode Solution image

Problem Statement of Number of Even and Odd Bits

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

Complexity Analysis

  • Time Complexity: O(\log n)
  • Space Complexity: O(1)

2595. Number of Even and Odd Bits LeetCode Solution in C++

class Solution {
 public:
  vector<int> evenOddBit(int n) {
    vector<int> ans(2);
    int i = 0;  // 0 := even, 1 := odd

    while (n > 0) {
      ans[i] += n & 1;
      n >>= 1;
      i ^= 1;
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

2595. Number of Even and Odd Bits LeetCode Solution in Java

class Solution {
  public int[] evenOddBit(int n) {
    int[] ans = new int[2];
    int i = 0; // 0 := even, 1 := odd

    while (n > 0) {
      ans[i] += n & 1;
      n >>= 1;
      i ^= 1;
    }

    return ans;
  }
}
// code provided by PROGIEZ

2595. Number of Even and Odd Bits LeetCode Solution in Python

class Solution:
  def evenOddBit(self, n: int) -> list[int]:
    ans = [0] * 2
    i = 0  # 0 := even, 1 := odd

    while n > 0:
      ans[i] += n & 1
      n >>= 1
      i ^= 1

    return ans
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.