@@ -65,22 +65,22 @@ func evenOddBit(n int) []int {
65
65
66
66
利用位掩码 ` 0x55555555 ` (二进制 $0101\cdots 01$),与 $n$ 计算 AND,即可取出所有偶数下标比特,然后用库函数统计其中 $1$ 的个数。
67
67
68
- 把 ` 0x55555555 ` 左移一位 (二进制 $1010\cdots 10$),与 $n$ 计算 AND,即可取出所有奇数下标比特,然后用库函数统计其中 $1$ 的个数。
68
+ 我们把 ` 0x55555555 ` 取反 (二进制 $1010\cdots 10$),与 $n$ 计算 AND,即可取出所有奇数下标比特,然后用库函数统计其中 $1$ 的个数。
69
69
70
70
> 注:因为 $n$ 比较小,你也可以用 `0x555 ` 作为位掩码。
71
71
72
72
```py [sol-Python3]
73
73
class Solution :
74
74
def evenOddBit(self, n: int) -> List[ int] :
75
75
MASK = 0x55555555
76
- return [ (n & MASK).bit_count(), (n & ( MASK << 1) ).bit_count()]
76
+ return [ (n & MASK).bit_count(), (n & ~ MASK).bit_count()]
77
77
```
78
78
79
79
```java [sol-Java]
80
80
class Solution {
81
81
public int[] evenOddBit(int n) {
82
82
final int MASK = 0x55555555;
83
- return new int[]{Integer.bitCount(n & MASK), Integer.bitCount(n & ( MASK << 1) )};
83
+ return new int[]{Integer.bitCount(n & MASK), Integer.bitCount(n & ~ MASK)};
84
84
}
85
85
}
86
86
```
@@ -90,15 +90,15 @@ class Solution {
90
90
public:
91
91
vector<int > evenOddBit(int n) {
92
92
const unsigned MASK = 0x55555555u;
93
- return {popcount(n & MASK), popcount(n & ( MASK << 1) )};
93
+ return {popcount(n & MASK), popcount(n & ~ MASK)};
94
94
}
95
95
};
96
96
```
97
97
98
98
```go [sol-Go]
99
99
func evenOddBit(n int) []int {
100
100
const mask = 0x55555555
101
- return []int{bits.OnesCount(uint(n & mask)), bits.OnesCount(uint(n & ( mask << 1) ))}
101
+ return []int{bits.OnesCount(uint(n & mask)), bits.OnesCount(uint(n & ^ mask))}
102
102
}
103
103
```
104
104
0 commit comments