From 246fbade63815352994d2750fb1137dd80b365c8 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Sat, 11 Jun 2022 12:44:46 +0100 Subject: [PATCH] guess-number-higher-or-lower --- guess-number-higher-or-lower/sol.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 guess-number-higher-or-lower/sol.rs diff --git a/guess-number-higher-or-lower/sol.rs b/guess-number-higher-or-lower/sol.rs new file mode 100644 index 0000000..fc97328 --- /dev/null +++ b/guess-number-higher-or-lower/sol.rs @@ -0,0 +1,22 @@ +/** + * 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 + * unsafe fn guess(num: i32) -> i32 {} + */ +impl Solution { + unsafe fn guessNumber(n: i32) -> i32 { + let (mut min, mut max) = (1, n); + while min != max { + let guess_num = max / 2 + min / 2; + match guess(guess_num) { + -1 => max = guess_num - 1, + 1 => min = guess_num + 1, + _ => return guess_num + } + } + min + } +} \ No newline at end of file