Advertisement
sweet1cris

Untitled

Feb 9th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.79 KB | None | 0 0
  1.  
  2. // version: 高频题班
  3.  
  4. /* The guess API is defined in the parent class GuessGame.
  5.    @param num, your guess
  6.    @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
  7.       int guess(int num); */
  8.  
  9. public class Solution extends GuessGame {
  10.     /**
  11.      * @param n an integer
  12.      * @return the number you guess
  13.      */
  14.     public int guessNumber(int n) {
  15.         // Write your code here
  16.         int l = 1, r = n;
  17.         while (l <= r) {
  18.             int mid = l + (r - l) / 2;
  19.             int res = guess(mid);
  20.             if (res == 0) {
  21.                 return mid;
  22.             }
  23.            
  24.             if (res == -1) {
  25.                 r = mid - 1;
  26.             } else {
  27.                 l = mid + 1;
  28.             }
  29.         }
  30.         return -1;
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement