Posted on

Description

Submission

class Solution {
public:
    double myPow(double x, long n) {
        if(abs(x - 1) < 1e-10) return 1;
        bool isNeg = false;
        if(n < 0) {
            isNeg = true;
            n = -n;
        }
        if(abs(x + 1) < 1e-10) {
            return (n % 2 == 1) ? -1 : 1;
        }
        double res = 1;
        while(n--) {
            res *= x;
            if(abs(res) < 1e-10) {
                res = 0;
                break;
            }
            if(isNeg && res > 1e10) return 0;
        }
        return isNeg ? 1 / res : res;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *