[LeetCode] Number of Even and Odd Bits

2595. 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 (0-indexed) with value 1.

Let odd denote the number of odd indices in the binary representation of n (0-indexed) with value 1.

Return an integer array answer where answer = [even, odd].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
vector<int> evenOddBit(int n) {
long long bit = 1;
int e = 0, o = 0;
for(long long i = 0; i < 32; i++) {
if(n & bit) {
if(i % 2) o += 1;
else e += 1;
}
bit *= 2;
}
return {e,o};
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/03/19/PS/LeetCode/number-of-even-and-odd-bits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.