This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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(int n) { | |
if (n < 2) { | |
return n; | |
} | |
// core logic | |
int start = 1; | |
int end = n; | |
while(start + 1 < end) { | |
int mid = (end - start) / 2 + start; | |
int tmpResult = guess(mid); | |
if (tmpResult == -1) { | |
end = mid; | |
} else if (tmpResult == 1) { | |
start = mid; | |
} else { | |
return mid; | |
} | |
} | |
if (guess(start) == 0) { | |
return start; | |
} else { | |
return end; | |
} | |
} | |
} |
No comments:
Post a Comment