December 27, 2021

50. Pow(x, n)

50. Pow(x, n)

Solution1: Brute Force

Multiply x for n times. Time: O(n), Space: O(1)

Solution2: Recursion

Time: O(logn), Space: O(logn)

class Solution {
    public double myPow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        if (n < 0) {
            // return 1 / myPow(x, -n);
            // avoid int overflow.
            return (1 / x) * myPow(1 / x, -(n + 1));
        }
        double half = myPow(x, n / 2);
        if (n % 2 == 0) {
            return half * half;
        } else {
            return half * half * x;
        }
    }
}
comments powered by Disqus