Title Description: From the 1~n, casually take out a number, you come to guess. Tips
Provides an API for guess (int num), which returns three values for guessing numbers. 0,-1,1
- 0. Guess return num
- -1: Smaller than the guessed value
- 1: Larger than the guessed value
For example:
n = ten, I pick 6.
Return 6.
Original Description:
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.
Thinking Analysis:
- Obviously is the application of the dichotomy, about the dichotomy, look at my previous blog, the more detailed, the link is as follows:
The implementation of the Java language binary method
Code:
/ * The Guess API is defined in the parent class Guessgame. @param num, your guess @return-1 If my number is lower, 1 if my number is higher, otherwise return 0 int guess (int NUM); */ Public class solution extends guessgame { Public int Guessnumber(intN) {intL =1, R = n; while(L <= R) {intMID = L + ((r-l) >>1);intres = guess (mid);if(res = =0)returnMidElse if(res = =1) L = mid +1;ElseR = mid-1; }returnL }}
For more leetcode topics, please see my leetcode column. The links are as follows:
Leetcode column
My QR code is as follows, welcome to exchange discussion
You are welcome to pay attention to the "It question summary" subscription number. Every day to push the classic face test and interview tips, are dry! The QR code of the subscription number is as follows:
"Leetcode73" Classic algorithm-guess number higher or Lower