diff --git a/leetcode/801-900/0868.Binary-Gap/README.md b/leetcode/801-900/0868.Binary-Gap/README.md index 1d8485fd2..358382a1f 100644 --- a/leetcode/801-900/0868.Binary-Gap/README.md +++ b/leetcode/801-900/0868.Binary-Gap/README.md @@ -1,28 +1,38 @@ # [868.Binary Gap][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 a positive integer `n`, find and return the **longest distance** between any two **adjacent** `1`'s in the binary representation of `n`. If there are no two adjacent `1`'s, return `0`. + +Two `1`'s are **adjacent** if there are only `0`'s separating them (possibly no `0`'s). The **distance** between two `1`'s is the absolute difference between their bit positions. For example, the two `1`'s in `"1001"` have a distance of 3. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: n = 22 +Output: 2 +Explanation: 22 in binary is "10110". +The first adjacent pair of 1's is "10110" with a distance of 2. +The second adjacent pair of 1's is "10110" with a distance of 1. +The answer is the largest of these two distances, which is 2. +Note that "10110" is not a valid pair since there is a 1 separating the two 1's underlined. ``` -## 题意 -> ... +**Example 2:** -## 题解 - -### 思路1 -> ... -Binary Gap -```go +``` +Input: n = 8 +Output: 0 +Explanation: 8 in binary is "1000". +There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0. ``` +**Example 3:** + +``` +Input: n = 5 +Output: 2 +Explanation: 5 in binary is "101". +``` ## 结语 diff --git a/leetcode/801-900/0868.Binary-Gap/Solution.go b/leetcode/801-900/0868.Binary-Gap/Solution.go index d115ccf5e..881c59a0c 100644 --- a/leetcode/801-900/0868.Binary-Gap/Solution.go +++ b/leetcode/801-900/0868.Binary-Gap/Solution.go @@ -1,5 +1,21 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(n int) int { + ans, count := 0, 0 + first := true + for ; n > 0; n >>= 1 { + if n&1 == 0 { + if !first { + count++ + } + continue + } + if first { + first = false + } else { + ans = max(ans, count) + } + count = 1 + } + return ans } diff --git a/leetcode/801-900/0868.Binary-Gap/Solution_test.go b/leetcode/801-900/0868.Binary-Gap/Solution_test.go index 14ff50eb4..8a5be7f04 100644 --- a/leetcode/801-900/0868.Binary-Gap/Solution_test.go +++ b/leetcode/801-900/0868.Binary-Gap/Solution_test.go @@ -10,12 +10,12 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs int + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", 22, 2}, + {"TestCase2", 8, 0}, + {"TestCase3", 5, 2}, } // 开始测试 @@ -30,10 +30,10 @@ func TestSolution(t *testing.T) { } } -// 压力测试 +// 压力测试 func BenchmarkSolution(b *testing.B) { } -// 使用案列 +// 使用案列 func ExampleSolution() { }