Topic:
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.
Answer:
Two-point search ideas
1 //Forward Declaration of the Guess API.2 //@param num, your guess3 //@return-1 If my number is lower, 1 if my number is higher, otherwise return 04 intGuessintnum);5 6 classSolution {7 Public:8 intGuessnumber (intN) {9 intlow=1, high=N;Ten intmid; One while(low<=High ) { Amid=low+ (high-low)/2;//Direct Write mid= (Low+high)/2 overflow - if(Guess (mid) = =0){ - returnmid; the } - Else if(Guess (mid) ==-1){ -high=mid-1; - } + Else{ -Low=mid+1; + } A } at returnmid; - } -};
374. Guess number Higher or Lower