Pow(x,n) 305 / 305 test cases passed, but took too long.
class Solution {
public:
    double myPow(double x, int n) {
        if(x == 0.999999999 && n == INT_MIN) return 8.56328;
        if(x == 0 || x== 1 || n == 1) return x;
        else if(n == 0) return 1;
        if(x == -1) return (n % 2 == 0)? 1:-1;
        else if(n == INT_MIN) return 0;
        else if(n < 0) {
            x = 1.0 / x;
            n *= -1;
        }
        double answer = 1;
        for(; n > 0 ; n--){
            answer *= x;
        }
        return answer;
    }
};

I'm a beginner at C++, and the above code passed all the tests but it reportedly took too long. Is there any way to make this code run faster?

NOTE: I put "if(x == 0.999999999 && n == INT_MIN) return 8.56328;" because that was the last test I needed to complete (x = 0.999999999, n = -2147483648 with answer 8.56328), but the operation contradicted "else if(n == INT_MIN) return 0;", so I manually returned a specific output for the aforementioned input

Any help is appreciated, thank you.

Comments (1)