diff --git a/leetcode/1001-1100/1017.Convert-to-Base--2/README.md b/leetcode/1001-1100/1017.Convert-to-Base--2/README.md index 4efb041f0..5907e6410 100644 --- a/leetcode/1001-1100/1017.Convert-to-Base--2/README.md +++ b/leetcode/1001-1100/1017.Convert-to-Base--2/README.md @@ -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] diff --git a/leetcode/1001-1100/1017.Convert-to-Base--2/Solution.go b/leetcode/1001-1100/1017.Convert-to-Base--2/Solution.go index d115ccf5e..8a8a82ce5 100644 --- a/leetcode/1001-1100/1017.Convert-to-Base--2/Solution.go +++ b/leetcode/1001-1100/1017.Convert-to-Base--2/Solution.go @@ -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) + } diff --git a/leetcode/1001-1100/1017.Convert-to-Base--2/Solution_test.go b/leetcode/1001-1100/1017.Convert-to-Base--2/Solution_test.go index 14ff50eb4..1d3347abe 100644 --- a/leetcode/1001-1100/1017.Convert-to-Base--2/Solution_test.go +++ b/leetcode/1001-1100/1017.Convert-to-Base--2/Solution_test.go @@ -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"}, } // 开始测试 @@ -30,10 +30,10 @@ func TestSolution(t *testing.T) { } } -// 压力测试 +// 压力测试 func BenchmarkSolution(b *testing.B) { } -// 使用案列 +// 使用案列 func ExampleSolution() { }