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.
Test instructions: Guess a number, according to the order of the dichotomy, guess the big time reminder 1, guess the hour reminder-1, guess the time to remind 0, Q: What is the number in the Guess?
Idea: According to the order of dichotomy to guess, according to the size of the hint to choose the left or right half of the part.
Java:
public class Solution extends Guessgame {public int guessnumber (int n) { int left=1;int right=n; while (left<=right)//According to the dichotomy of { int number=left+ (right-left)/2; Count=guess (number); if (count==0) return number;//guess on the direct return to else if (count==1)//Guess large, select the left half left=number+1; else {right=number-1;//Guess the right half of the hour to select} } return-1;}}
374. Guess number higher or Lower java