Corner case for java


  • 0

    The same method works for C++ but not Java because of this corner case:-2147483648. Could any smart people help with it??? Really appreciate it!

    public class Solution {
        public double myPow(double x, int n) { // Time Limit Exceeded 
            if ( n < 0 ) {
                return 1.0/power ( x, -n);
            }
            return power( x, n );
        }
        public double power ( double x, int n ) {
            if ( n == 0 ) {return 1;}
            double v = power ( x, n/2 );
            return (n%2==1? (v * v * x) : (v * v));
        }
    }
    

    Here is the only case I didn't pass:

    Input:
    2.00000
    -2147483648
    Output:
    1.00000
    Expected:
    0.00000
    

  • 0
    U

    My solution is as followed, which is quite similar to yours.
    The difference is that I deal with negative n at the end of the recursions, not at the front.

        public double myPow(double x, int n) {
            double ans = biPow(x, n);
            if(n < 0) ans = 1/ans;
            return ans;
        }
        
        public double biPow(double x, int n) {
            if(n == 0) return 1;
            if(n == 1 || n == -1) return x;
            double ans = biPow(x, n/2);
            if(n % 2 == 0) {
                return ans * ans;
            } else {
                return ans * ans * x;
            }
        } 
    

Log in to reply
 

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