We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You had to guess which number I picked.
Every time you guess wrong, I'll tell you whether the number is higher or lower.
you call a pre-defined api guess (int num)
which returns 3 possible results (-1
, 1
, Or 0
):
-1:my number is lower 1:my number is higher 0:congrats! You got it!
Example:
n = ten, I pick 6.Return 6.
Subscribe to see which companies asked this question
Hide TagsBinary SearchShow Similar Problems
Analysis:
This is probably the simplest of two-faceted questions!
Forward declaration of Guess api.//@param num, your guess//@return-1 If my number is lower, 1 if my number is higher , otherwise return 0int guess (int num); class Solution {public: int guessnumber (int n) { int mid=0,left=1,right=n; While (left < right) { mid=left+ (right-left)/2; if (Guess (mid) ==0) return mid; else if (guess (mid) = = 1) left=mid+1; else right=mid-1; } return left; }};
Note: This blog post is Ebowtang original and may continue to be updated later in this article. If reproduced, please make sure to copy this article information!
Original address: http://blog.csdn.net/ebowtang/article/details/51812032
Original Author Blog: Http://blog.csdn.net/ebowtang
This blog leetcode key index: http://blog.csdn.net/ebowtang/article/details/50668895
<leetcode oj> 374. Guess number Higher or Lower