不定期更新leetcode解题java答案。
采用pick one的方式选择题目。
题意为给定一个范围,1~N,给定一个固定数,随机进行猜数,尽快用程序获取猜得结果。每次猜错会给出猜想大了(返回-1)或小了(返回1)的提示。
很容易想到用二分进行猜数(需要注意的是为了防止两数相加和超出int的上限,分开进行处理),代码如下:
1 /* The guess API is defined in the parent class GuessGame. 2 @param num, your guess 3 @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 4 int guess(int num); */ 5 6 public class Solution extends GuessGame { 7 public int guessNumber(int n) { 8 int start = 0, end = n, guessNum = 0; 9 int result = 1; 10 while(result != 0){ 11 if(result == 1) 12 start = guessNum; 13 else 14 end = guessNum; 15 guessNum = start / 2 + end / 2 + (start % 2 + end % 2 == 0 ? 0 : 1); 16 17 result = guess(guessNum); 18 } 19 return guessNum; 20 } 21 }