It is also a subject of API calls by guessing the size of the dichotomy. Note that the boundary is judged from 1 to N. This question does not provide a JavaScript API so I direct the Java code.
Time O (logn)
Space O (1)
1 /* The guess API is defined in the parent class GuessGame. 2 @param num, your guess 3 @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 4 int guess(int num); */ 5 6 public class Solution extends GuessGame { 7 public int guessNumber(int n) { 8 int start = 1; 9 int end = n; 10 while (start + 1 < end) { 11 int mid = start + (end - start) / 2; 12 if (guess(mid) == 0) { 13 return mid; 14 } else if (guess(mid) == 1) { 15 start = mid; 16 } else { 17 end = mid; 18 } 19 } 20 if (guess(start) == 0) return start; 21 return end; 22 } 23 }