1. 程式人生 > >LintCode 662. 猜數遊戲

LintCode 662. 猜數遊戲

num ram ati 個數 每次 二分法 ntc api IT

我們正在玩猜數遊戲。 遊戲如下:
我從 1 到 n 選擇一個數字。 你需要猜我選擇了哪個號碼。
每次你猜錯了,我會告訴你這個數字是高還是低。
你調用一個預定義的接口 guess(int num),它會返回 3 個可能的結果(-1,1或0):

樣例
n = 10, 我選擇了 4 (但是你不知道)
返回 4。正確!

思路:簡單題,二分法,需要註意的是取中間值的時候用(a+b)/2會導致int溢出,改成mid = a+(b-a)/2就行了。

 1 // Forward declaration of guess API.
 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 class Solution { 7 public: 8 /** 9 * @param n an integer 10 * @return the number you guess 11 */ 12 int guessNumber(int n) { 13 // Write your code here 14 int start = 1; 15 int end = n; 16 int res = start + (end - start)/2
;//取中間值需要寫成這樣 17 while(1){ 18 int ret = guess(res); 19 if(!ret) break; 20 else if(ret == 1) start = res+1; 21 else end = res-1; 22 res = start + (end - start)/2; 23 } 24 return res; 25 } 26 };

LintCode 662. 猜數遊戲