guess-number-higher-or-lower

This commit is contained in:
Gleb Koval 2022-06-11 12:44:46 +01:00
parent b1a05f3db7
commit 246fbade63
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
1 changed files with 22 additions and 0 deletions

View File

@ -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
}
}