Skip to content

Commit 97d5965

Browse files
committed
简化代码
1 parent ee327a2 commit 97d5965

File tree

2 files changed

+6
-6
lines changed

2 files changed

+6
-6
lines changed

leetcode/weekly/337/a/README.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,22 +65,22 @@ func evenOddBit(n int) []int {
6565

6666
利用位掩码 `0x55555555`(二进制 $0101\cdots 01$),与 $n$ 计算 AND,即可取出所有偶数下标比特,然后用库函数统计其中 $1$ 的个数。
6767

68-
`0x55555555` 左移一位(二进制 $1010\cdots 10$),与 $n$ 计算 AND,即可取出所有奇数下标比特,然后用库函数统计其中 $1$ 的个数。
68+
我们把 `0x55555555` 取反(二进制 $1010\cdots 10$),与 $n$ 计算 AND,即可取出所有奇数下标比特,然后用库函数统计其中 $1$ 的个数。
6969

7070
> 注:因为 $n$ 比较小,你也可以用 `0x555` 作为位掩码。
7171

7272
```py [sol-Python3]
7373
class Solution:
7474
def evenOddBit(self, n: int) -> List[int]:
7575
MASK = 0x55555555
76-
return [(n & MASK).bit_count(), (n & (MASK << 1)).bit_count()]
76+
return [(n & MASK).bit_count(), (n & ~MASK).bit_count()]
7777
```
7878
7979
```java [sol-Java]
8080
class Solution {
8181
public int[] evenOddBit(int n) {
8282
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)};
8484
}
8585
}
8686
```
@@ -90,15 +90,15 @@ class Solution {
9090
public:
9191
vector<int> evenOddBit(int n) {
9292
const unsigned MASK = 0x55555555u;
93-
return {popcount(n & MASK), popcount(n & (MASK << 1))};
93+
return {popcount(n & MASK), popcount(n & ~MASK)};
9494
}
9595
};
9696
```
9797
9898
```go [sol-Go]
9999
func evenOddBit(n int) []int {
100100
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))}
102102
}
103103
```
104104

leetcode/weekly/337/a/a.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,5 @@ import "math/bits"
55
// https://space.bilibili.com/206214
66
func evenOddBit(n int) []int {
77
const mask = 0x55555555
8-
return []int{bits.OnesCount(uint(n & mask)), bits.OnesCount(uint(n & (mask << 1)))}
8+
return []int{bits.OnesCount(uint(n & mask)), bits.OnesCount(uint(n & ^mask))}
99
}

0 commit comments

Comments
 (0)