Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit d496b1d

Browse files
aQuaaQua
aQua
authored and
aQua
committed
600 finish
1 parent aae53c9 commit d496b1d

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,44 @@
11
package Problem0600
22

33
func findIntegers(num int) int {
4-
res := 5
4+
// binaries 是 num 的二进制表示,逆序
5+
binary := make([]byte, 0, 32)
6+
for num > 0 {
7+
binary = append(binary, byte(num%2)+'0')
8+
num /= 2
9+
}
10+
11+
n := len(binary)
12+
// a[i] == 长度为 i+1 且以 0 结尾的 binary 中不包含连续 1 的个数
13+
a := make([]int, n)
14+
// b[i] == 长度为 i+1 且以 1 结尾的 binary 中不包含连续 1 的个数
15+
b := make([]int, n)
16+
a[0] = 1
17+
b[0] = 1
18+
19+
for i := 1; i < n; i++ {
20+
// 在 a[i-1] 中的 binary 右边加 0
21+
// 和
22+
// 在 b[i-1] 中的 binary 右边加 0
23+
// 可以得到 a[i] 中的 binary
24+
a[i] = a[i-1] + b[i-1]
25+
// 在 a[i-1] 中的 binary 右边加 1,可以得到 b[i] 中的 binary
26+
// 在 b[i-1] 中的 binary 右边加 1 会得到连续的 1,违反了题意
27+
b[i] = a[i-1]
28+
}
29+
30+
res := a[n-1] + b[n-1]
31+
// 此时的 res 可能包含了 >num 的那一部分数,需要减去相关部分
32+
for i := n - 1; i-1 > 0; i-- {
33+
// 注意,此时的 binary 是逆序
34+
// 出现连续的 `1` 说明已经清理干净了
35+
if binary[i-1] == '1' && binary[i] == '1' {
36+
break
37+
}
38+
// 当初多加了 b[i]
39+
if binary[i-1] == '0' && binary[i] == '0' {
40+
res -= b[i]
41+
}
42+
}
543
return res
644
}

Algorithms/0600.non-negative-integers-without-consecutive-ones/non-negative-integers-without-consecutive-ones_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ var tcs = []struct {
1313
ans int
1414
}{
1515

16+
{1000, 144},
17+
18+
{8, 6},
19+
1620
{5, 5},
1721

1822
// 可以有多个 testcase

0 commit comments

Comments
 (0)