Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2431 from galfudim/gfudim-rust-0374
Browse files Browse the repository at this point in the history
Create: 374-Guess-Number-Higher-or-Lower.rs
  • Loading branch information
tahsintunan authored Aug 4, 2023
2 parents 1758552 + f331e0f commit 532626e
Showing 1 changed file with 26 additions and 0 deletions.
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
}
}
}

0 comments on commit 532626e

Please sign in to comment.