can someone tell me why the same code, one pass and one fail???


  • 0
    A

    double myPow(double x, int n) {
    if (x == 0) return 0.0;
    if (n < 0)
    {
    long long temp = -n;
    return myPow(1/x, temp);
    }
    return helper(x, n);
    }

    double helper(double x, long long n)
    {
        if (n == 1) return x;
        if (n == 0) return 1;
        double temp = helper(x, n/2);
        if (n%2 == 1) return temp * temp * x;
        return temp * temp;
    }
    
    /**
     * This works. Why?
     */
    double myPow1(double x, int n) {
        if (x == 0) return 0;
        if (n < 0) return recursive(1/x, -n);
        return recursive(x, n);
    }
    
    double recursive(double x, int n) {
        if (n == 1) return x;
        if (n == 0) return 1;
        if (n%2 == 0) {
            double temp = recursive(x, n/2);
            return temp*temp;
        }
        else {
            double temp = recursive(x, n/2);
            return temp*temp*x;
        }
    }

  • 0
    C

    I have the similar problem. I think it because of the sequence of (n % 2 == 0) and (n % 2 == 1)
    But I don't know the further cause.


  • 0
    C

    sorry, its not about the sequence, but about the if statement. if(n % 2 == 0) is ok, if(n % 2 == 1) is wrong


  • 0
    C

    because 2147483648 % 2 == -1


  • 0
    A

    @codermin cool. thanks very much


Log in to reply
 

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