Skip to content

2595. Number of Even and Odd BitsΒΆ

  • Time: O(log⁑n)O(\log n)
  • Space: O(1)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
Buy Me A Coffee
Thanks for stopping by! If you find this site helpful, consider buying me some protein powder to keep me fueled! πŸ˜„