374. Guess Number Higher or Lower

Inequality-Sign發表於2018-03-21

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have 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 = 10, I pick 6.

Return 6.

就是一個二分法找數的題

public int guessNumber(int n) {
        int low = 1;
        int high = n;
        int mid = low + (high - low) / 2;
        while (low < high) {
            if(guess(mid) == 0) return mid;
            else if(guess(mid) == -1)high = mid;
            else if(guess(mid) == 1)low = mid+1;
        }
        return low;
    }

計算mid的時候一定要寫成 mid = low +(high - low) / 2;
而不要寫成mid = (low + high)/2
因為第二種有可能會造成溢位,謹記

相關文章