TopCoder练习题笔记01
TopCoder01 SRM 157 DIV2 250分:
Problem Statement | |||||||||||||
A popular guessing game is "Guess the number", where one person selects a number in a known range, and another person tries to guess that number. After each guess, the first person reveals whether the guess was correct, too high or too low. Pretty soon one learns the best strategy, which is to guess the middle number among those not yet ruled out. If there is no single middle number, then there are two numbers to choose from. In that case, we choose the smallest of those numbers. The algorithm can be described like this: Init lower and upper bound Repeat x = (lower bound + upper bound)/2 (round down if necessary) Make guess x If x is too low, set lower bound to x+1 If x is too high, set upper bound to x-1 Until x is correct For instance, assume that the lower and upper bound initally are 1 and 9, respectively. The middle number in this range is 5. If this is "too low", the new bounds become 6 and 9. This range contains four numbers, and there is thus no single middle number. The two numbers in the middle are 7 and 8, and the smallest of these is 7, so our next guess then becomes 7. Create a class GuessTheNumber which contains the method noGuesses which takes an int upper, the initial upper bound of the range (the inital lower bound is always 1), and an int answer, the number selected by the first person. The method should return an int representing the total number of guesses required for the second person to guess the correct number using the method described above. | |||||||||||||
Definition | |||||||||||||
|
大概提议就是有个一游戏,A记下一个数字,B给出一个数字去猜是不是A的数字,如果B给出的数字比A记下的数字要大,A就说:“大了”,B继续去猜知道才对为止
上面给出了详细的算法:
Init lower and upper bound Repeat x = (lower bound + upper bound)/2 (round down if necessary) Make guess x If x is too low, set lower bound to x+1 If x is too high, set upper bound to x-1 Until x is correct只需要翻译成JAVA语言即可:
我写的方法如下:
public class GuessTheNumber {
int count;
public int noGuesses(int low,int answer,int high){
int x = (low+high)/2;
if(x==answer){
return ++count;
}
else if(answer>x){
noGuesses(x+1,answer,high);
++count;
}else{
noGuesses(low,answer,x-1);
++count;
}
return count;
}
public int noGuesses(int upper,int answer){
return noGuesses(1,answer,upper);
}
}
使用递归实现,但感觉有很多可以改进的地方,于是看了下满分大神写的,如下:
public int noGuesses(int upper,int answer){
int low = 1, count = 0, middle=0;
while(true){
middle = (low+upper)/2;
count++;
if(middle == answer){
break;
}else if(middle>answer){
upper = middle-1;
}else{
low = middle+1;
}
}//while
return count;
}//method
确实简单不少,也更易懂,这个练习让我知道,递归可以使用循环模式来写,需要让循环成为死循环,同时要在循环体中写上跳出循环的条件,此练习还可以使用For循环去实现和上面While循环大同小异,就不再赘述