Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 17 additions & 14 deletions leetcode/1001-1100/1017.Convert-to-Base--2/README.md
Original file line number Diff line number Diff line change
@@ -1,30 +1,33 @@
# [1017.Convert to Base -2][title]

> [!WARNING|style:flat]
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)

## Description
Given an integer `n`, return a binary string representing its representation in base `-2`.

**Note** that the returned string should not have leading zeros unless the string is `"0"`.

**Example 1:**

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

## 题意
> ...

## 题解
**EXample 2:**

### 思路1
> ...
Convert to Base -2
```go
```
Input: n = 3
Output: "111"
Explantion: (-2)2 + (-2)1 + (-2)0 = 3
```

**Example 3:**

## 结语
```
Input: n = 4
Output: "100"
Explantion: (-2)2 = 4
```

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

Expand Down
22 changes: 20 additions & 2 deletions leetcode/1001-1100/1017.Convert-to-Base--2/Solution.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
package Solution

func Solution(x bool) bool {
return x
func Solution(n int) string {
if n == 0 {
return "0"
}
var result []byte
for n != 0 {
remainder := n % -2
n = n / -2

if remainder < 0 {
remainder += 2
n += 1
}
result = append(result, byte(remainder+48))
}
for s, e := 0, len(result)-1; s < e; s, e = s+1, e-1 {
result[s], result[e] = result[e], result[s]
}
return string(result)

}
14 changes: 7 additions & 7 deletions leetcode/1001-1100/1017.Convert-to-Base--2/Solution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
inputs int
expect string
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", 2, "110"},
{"TestCase2", 3, "111"},
{"TestCase3", 4, "100"},
}

// 开始测试
Expand All @@ -30,10 +30,10 @@ func TestSolution(t *testing.T) {
}
}

// 压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
// 使用案列
func ExampleSolution() {
}
Loading