[LeetCode] 50. Pow(x, n) 求x的n次方
Implement pow(x, n).
求x的n次幂,如果用n个循环相乘,那就太简单了,肯定不是这题要考察的。
解法:利用性质:
n是奇数,n % 2 == 1, x^n = x^(n/2) * x^(n/2) * x;
n是偶数,n % 2 == 0, x^n = x^(n/2) * x^(n/2);
每次n/2,递归到下一层,直到n=0是返回1。 如果n为负数,利用x^-n = 1/x^n。
Java:
class Solution { public double myPow(double x, int n) { if(n < 0) return 1 / pow(x, -n); else return pow(x, n); } public double pow(double x, int n){ if(n == 0) return 1; double mid=pow(x, n / 2); if((n & 1) == 0) return mid * mid; else return mid * mid * x; } }
Python: Recursion, T: O(logn), S: O(logn)
class Solution(object): def myPow(self, x, n): if n < 0 and n != -n: return 1.0 / self.myPow(x, -n) if n == 0: return 1 v = self.myPow(x, n / 2) if n % 2 == 0: return v * v else: return v * v * x
Python: Iteration, T: O(logn), S: O(1)
class Solution(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ result = 1 abs_n = abs(n) while abs_n: if abs_n & 1: result *= x abs_n >>= 1 x *= x return 1 / result if n < 0 else result
C++:
class Solution { public: double myPow(double x, int n) { if (n < 0) return 1 / power(x, -n); return power(x, n); } double power(double x, int n) { if (n == 0) return 1; double half = power(x, n / 2); if (n % 2 == 0) return half * half; return x * half * half; } };
类似题目:
All LeetCode Questions List 题目汇总