Simple c++ solution using 2^k-ary


  • 5
    N
    class Solution {
    public:
        double myPow(double x, int n) {
            double ret = 1;
            if (n < 0){
                n *= -1;
                x = 1 / x;
            }
            while (n > 0){
                if (n & 1) ret *= x;
                x = x * x;
                n >>= 1;
            }
            return ret;
        }
    };

  • 1
    T

    what about the condition that n = -2147483648, and in this circumstance n*-1 = n for n is int32. And the result is wrong.


Log in to reply
 

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