Pow(x, n)
Input: 2.00000, 10
Output: 1024.00000Input: 2.10000, 3
Output: 9.26100Basic Idea:
class Solution { public double myPow(double x, int n) { if (x == 0 || x == 1) return x; else if (n == 0) return 1; if (n < 0) { return helper(1 / x, -(long)n); // 这里用long是为了处理当n为 -2147483648 的情况,避免overflow } else { return helper(x, n); } } private double helper(double x, long n) { if (n == 1) return x; double pow = helper(x, n / 2); if (n % 2 != 0) { return x * pow * pow; } else { return pow * pow; } } }class Solution { public double myPow(double x, int n) { if (x == 0 || x == 1) return x; else if (n == 0) return 1; long N = n; if (n < 0) { x = 1 / x; N = -(long)n; } double res = 1; double curr = x; while (N > 0) { if (N % 2 == 1) { res = res * curr; } curr *= curr; N /= 2; } return res; } }