A binary C++ solution without recurse


  • 1
    5
    double myPow(double x, int n) {
        unsigned int m = 1, n_tmp = n;
        if (n < 0) {
            n_tmp = -n;
            x = 1 / x;
        }
        int bFlag = 1;
        if (x < 0) {
            bFlag = (n_tmp & 0x1) ? -1 : 1;
            x = -x;
        }
        if (x == 1 || x == 0) {
            return bFlag * x;
        }
        if (n_tmp == 0) {
            return 1;
        }
        double result = 1;
        while (m <= n_tmp) {
            if (m & n_tmp) {
                result *= x;
            }
            x *= x;
            m <<= 1;
        }
        return bFlag * result;
    }

  • -8
    B

    This is the easiest code in history, I promise.
    double myPow(double x, int n) { pow(x, n); }


Log in to reply
 

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