Skip to content

Commit 9c4fb2d

Browse files
authored
Merge pull request #1311 from 0xff-dev/1017
Add solution and test-cases for problem 1017
2 parents a463f07 + 0320785 commit 9c4fb2d

File tree

3 files changed

+44
-23
lines changed

3 files changed

+44
-23
lines changed

leetcode/1001-1100/1017.Convert-to-Base--2/README.md

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,33 @@
11
# [1017.Convert to Base -2][title]
22

3-
> [!WARNING|style:flat]
4-
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)
5-
63
## Description
4+
Given an integer `n`, return a binary string representing its representation in base `-2`.
5+
6+
**Note** that the returned string should not have leading zeros unless the string is `"0"`.
77

88
**Example 1:**
99

1010
```
11-
Input: a = "11", b = "1"
12-
Output: "100"
11+
Input: n = 2
12+
Output: "110"
13+
Explantion: (-2)2 + (-2)1 = 2
1314
```
1415

15-
## 题意
16-
> ...
17-
18-
## 题解
16+
**EXample 2:**
1917

20-
### 思路1
21-
> ...
22-
Convert to Base -2
23-
```go
18+
```
19+
Input: n = 3
20+
Output: "111"
21+
Explantion: (-2)2 + (-2)1 + (-2)0 = 3
2422
```
2523

24+
**Example 3:**
2625

27-
## 结语
26+
```
27+
Input: n = 4
28+
Output: "100"
29+
Explantion: (-2)2 = 4
30+
```
2831

2932
如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]
3033

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,23 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
func Solution(n int) string {
4+
if n == 0 {
5+
return "0"
6+
}
7+
var result []byte
8+
for n != 0 {
9+
remainder := n % -2
10+
n = n / -2
11+
12+
if remainder < 0 {
13+
remainder += 2
14+
n += 1
15+
}
16+
result = append(result, byte(remainder+48))
17+
}
18+
for s, e := 0, len(result)-1; s < e; s, e = s+1, e-1 {
19+
result[s], result[e] = result[e], result[s]
20+
}
21+
return string(result)
22+
523
}

leetcode/1001-1100/1017.Convert-to-Base--2/Solution_test.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
14-
expect bool
13+
inputs int
14+
expect string
1515
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
16+
{"TestCase1", 2, "110"},
17+
{"TestCase2", 3, "111"},
18+
{"TestCase3", 4, "100"},
1919
}
2020

2121
// 开始测试
@@ -30,10 +30,10 @@ func TestSolution(t *testing.T) {
3030
}
3131
}
3232

33-
// 压力测试
33+
// 压力测试
3434
func BenchmarkSolution(b *testing.B) {
3535
}
3636

37-
// 使用案列
37+
// 使用案列
3838
func ExampleSolution() {
3939
}

0 commit comments

Comments
 (0)