Guessing a number knowing only if the number proposed is lower or higher?

前端 未结 7 981
悲哀的现实
悲哀的现实 2021-01-02 21:34

I need to guess a number. I can only see if the number I\'m proposing is lower or higher. Performance matters a whole lot, so I thought of the following algorithm:

Le

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-02 22:05

    int a = 1, b = n+1, guess = average of previous answers;
    
    while(guess is wrong) {
    
        if(guess lower than answer) {a = guess;}
        else if(guess higher than answer) {b = guess;}
    
        guess = (a+b)/2;
    
    } //Go back to while
    

    You got to add +1 to n else you can never get n since it's an int.

提交回复
热议问题