From 153b7b2c5e3039e042262065b574dd8f051e5306 Mon Sep 17 00:00:00 2001 From: ductnn Date: Sun, 10 Dec 2023 23:02:51 +0700 Subject: [PATCH] add sol --- .../guessNumberHigherOrLower.go | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 leetcode/leetcode75/374.GuessNumberHigherOrLower/guessNumberHigherOrLower.go diff --git a/leetcode/leetcode75/374.GuessNumberHigherOrLower/guessNumberHigherOrLower.go b/leetcode/leetcode75/374.GuessNumberHigherOrLower/guessNumberHigherOrLower.go new file mode 100644 index 0000000..8b20574 --- /dev/null +++ b/leetcode/leetcode75/374.GuessNumberHigherOrLower/guessNumberHigherOrLower.go @@ -0,0 +1,43 @@ +package main + +import ( + "fmt" +) + +/** + * Forward declaration of guess API. + * @param num your guess + * @return -1 if num is higher than the picked number + * 1 if num is lower than the picked number + * otherwise return 0 + * func guess(num int) int; + */ + +var pick = 6 + +func guess(num int) int { + if num == pick { + return 0 + } else if num > pick { + return -1 + } + return 1 +} + +func guessNumber(n int) int { + left, right := 1, n + for left < right { + mid := left + (right-left)>>1 + if guess(mid) <= 0 { + right = mid + } else { + left = mid + 1 + } + } + return left +} + +func main() { + n := 10 + fmt.Println(guessNumber(n)) +}