LeetCode:374. Guess Number Higher or Lower

 1 package day20170206;
 2 //LeetCode:374. Guess Number Higher or Lower
 3 /*
 4  We are playing the Guess Game. The game is as follows:
 5 I pick a number from 1 to n. You have to guess which number I picked.
 6 Every time you guess wrong, I'll tell you whether the number is higher or lower.
 7 You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
 8 
 9 -1 : My number is lower
10  1 : My number is higher
11  0 : Congrats! You got it!
12 Example:
13 n = 10, I pick 6.
14 
15 Return 6.
16  */
17 public class guessNumber374 {
18     /* The guess API is defined in the parent class GuessGame.
19        @param num, your guess
20        @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
21           int guess(int num); */
22 
23     public static int guessNumber(int n) {
24         if(guess(1)==0)
25             return 1;
26         else if(guess(n)==0)
27             return n;
28         else{
29             int left=1,right=n,mid;
30             while(left<right){
31                 mid=left+(right-left)/2;
32                 if(guess(mid)==0)
33                     return mid;
34                 else if(guess(mid)==1)
35                     left=mid+1;
36                 else 
37                     right=mid-1;
38             }
39             return left;
40         }
41     }
42     public static int guess(int n){
43         int num=1702766719;
44         //int num=6;
45         if(n==num)
46             return 0;
47         else if(n<num)
48             return 1;
49         else
50             return -1;
51     }
52     //竟然超时,然后就自己写了个guess测试,把mid=(left+right)/2换成mid=left+(right-left)/2 
53     //当数值太大,mid就会溢出,然后while语句就死循环了,所以就报超时的错了
54     //题目看了老半天才知道啥意思,也是醉了,guessNumber传入的参数是范围,我们只负责猜,返回的是猜中的数,guess会告诉我们猜的对不对,所以我们的程序要完成的就是猜的这个过程,如何遍历数
55     
56     //study  用(l & r) + ((l ^ r) >> 1)替换left+(right-left)/2 ,表示不能理解啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊
57     public static void main(String[] args) {
58         // TODO Auto-generated method stub
59         //System.out.println(guessNumber(10));
60         System.out.println(guessNumber(2126753390));
61     }
62 
63 }

 

posted @ 2017-02-07 10:03  蒲公英的花朵  阅读(208)  评论(0编辑  收藏  举报