Skip to content

2595. Number of Even and Odd Bits

  • Time: $O(\log n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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