Any wrong with my Java solution?


  • 0
    W

    following is my java code; it gives the correct answer in my PC, which is 6; but the submission gives 1; any wrong with my solution? or the java test case is broken?

    public int guessNumber(int n) {
            int i = 1;
            int j = n;
            while (i <= j) {
                int k = i + (j - i) / 2;
                int r = guess(k);
                if (r == 0) {
                    return k;
                }
    
                if (r < 0) {
                    i = k + 1;
                } else {
                    j = k - 1;
                }
            }
    
            return i;
        }
    
        private int guess(int k) {
            return k - 6;
        }
    

  • 0

    Why did you implement guess(int) function?


  • 1
    W

    @jedihy it is for testing only, will not submit;
    and I know what is wrong here,

    -1 : My number is lower
     1 : My number is higher
     0 : Congrats! You got it!
    

    I misunderstand "my number" as the number I am guessing, but it should be the given number;


  • 0
    W
    public int guessNumber(int n) {
            int i = 1;
            int j = n;
            while (i <= j) {
                int k = i + (j - i) / 2;
                int r = guess(k);
                if (r == 0) {
                    return k;
                }
    
                if (r > 0) {
                    i = k + 1;
                } else {
                    j = k - 1;
                }
            }
    
            return i;
        }
    ```
    
    the accepted solution;

  • 0
    Z

    @wang.senyuan
    Agree, this is a bit confusing at first glance.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.