Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions rust/0374-guess-number-higher-or-lower.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* 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 {
Self::binary_search(1, n)
}

unsafe fn binary_search(left: i32, right: i32) -> i32 {
let mid = left + (right - left ) / 2;

if guess(mid) < 0 {
Self::binary_search(1, mid)
} else if guess(mid) > 0 {
Self::binary_search(mid + 1, right)
} else {
mid
}
}
}