LeetCode problem#374
Guess Number Higher or Lower
Solved in 2 languagesJavaRust
Solution
32 lines
1/**
2 * Forward declaration of guess API.
3 * @param num your guess
4 * @return -1 if num is higher than the picked number
5 * 1 if num is lower than the picked number
6 * otherwise return 0
7 * int guess(int num);
8 */
9
10 public class Solution extends GuessGame {
11 public int guessNumber(int n) {
12 int lower = 1;
13 int higher = n;
14 while (lower <= higher) {
15 // This simplified expression will cause time limit exceeded.
16 // So either use long, or rewrite in a form that doesn't risk overflow.
17 // int mid = (higher + lower) / 2;
18 int mid = lower + (higher - lower) / 2;
19 int result = guess(mid);
20 if (result == 0) {
21 return mid;
22 }
23 else if (result > 0) {
24 lower = mid + 1;
25 }
26 else if (result < 0) {
27 higher = mid - 1;
28 }
29 }
30 return 0;
31 }
32}1/**
2 * Forward declaration of guess API.
3 * @param num your guess
4 * @return -1 if num is higher than the picked number
5 * 1 if num is lower than the picked number
6 * otherwise return 0
7 * unsafe fn guess(num: i32) -> i32 {}
8 */
9
10 impl Solution {
11 unsafe fn guessNumber(n: i32) -> i32 {
12 let mut lower = 1;
13 let mut higher = n;
14
15 while lower <= higher {
16 let mut mid = lower + (higher - lower) / 2;
17 let result = guess(mid);
18
19 if result == 0 {
20 return mid;
21 }
22 else if result > 0 {
23 lower = mid + 1;
24 }
25 else { // result < 0
26 higher = mid - 1;
27 }
28 }
29
30 return 0;
31 }
32}Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Want a walkthrough of this Rust solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.