|
16 | 16 |
|
17 | 17 | */
|
18 | 18 | public class _374 {
|
19 |
| - /**The core problem/trouble to solve this problem is to figure out the problem description: |
20 |
| - * this API: guess(int num) means to take your guess num and let you know if your guessed num is bigger or smaller than the answer. |
21 |
| - * That's why if num > target, it returns -1 which means the target is smaller than your guess!!!*/ |
| 19 | + public static class Solution1 { |
| 20 | + /** |
| 21 | + * The core problem/trouble to solve this problem is to figure out the problem description: this |
| 22 | + * API: guess(int num) means to take your guess num and let you know if your guessed num is |
| 23 | + * bigger or smaller than the answer. That's why if num > target, it returns -1 which means the |
| 24 | + * target is smaller than your guess!!! |
| 25 | + */ |
22 | 26 |
|
23 |
| - public int guessNumber(int n) { |
24 |
| - int left = 1; |
25 |
| - int right = n; |
26 |
| - while (left + 1 < right) { |
27 |
| - int mid = left + (right - left) / 2; |
28 |
| - int g = guess(mid); |
29 |
| - if (g == 0) { |
30 |
| - return mid; |
31 |
| - } else if (g > 0) { |
32 |
| - left = mid; |
33 |
| - } else { |
34 |
| - right = mid; |
| 27 | + public int guessNumber(int n) { |
| 28 | + int left = 1; |
| 29 | + int right = n; |
| 30 | + while (left + 1 < right) { |
| 31 | + int mid = left + (right - left) / 2; |
| 32 | + int g = guess(mid); |
| 33 | + if (g == 0) { |
| 34 | + return mid; |
| 35 | + } else if (g > 0) { |
| 36 | + left = mid; |
| 37 | + } else { |
| 38 | + right = mid; |
| 39 | + } |
35 | 40 | }
|
| 41 | + if (guess(left) == 0) { |
| 42 | + return left; |
| 43 | + } |
| 44 | + return right; |
36 | 45 | }
|
37 |
| - if (guess(left) == 0) { |
38 |
| - return left; |
39 |
| - } |
40 |
| - return right; |
41 |
| - } |
42 | 46 |
|
43 |
| - /** |
44 |
| - * This is a fake guess method that I wrote just to compile/test, I'll have to change it to another number other than 6 based on the number to be found. |
45 |
| - */ |
46 |
| - private int guess(int num) { |
47 |
| - if (num > 6) { |
48 |
| - return -1; |
49 |
| - } else if (num < 6) { |
50 |
| - return 1; |
51 |
| - } else { |
52 |
| - return 0; |
| 47 | + /** |
| 48 | + * This is a fake guess method that I wrote just to compile/test, I'll have to change it to |
| 49 | + * another number other than 6 based on the number to be found. |
| 50 | + */ |
| 51 | + private int guess(int num) { |
| 52 | + if (num > 6) { |
| 53 | + return -1; |
| 54 | + } else if (num < 6) { |
| 55 | + return 1; |
| 56 | + } else { |
| 57 | + return 0; |
| 58 | + } |
53 | 59 | }
|
54 | 60 | }
|
55 | 61 |
|
56 |
| - public static void main(String... strings) { |
57 |
| - _374 test = new _374(); |
58 |
| - System.out.println(test.guessNumber(1000)); |
59 |
| - } |
60 |
| - |
61 | 62 | }
|
0 commit comments