原题链接在这里:https://leetcode.com/problems/powx-n/
题目:
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10 Output: 1024.00000
Example 2:
Input: 2.10000, 3 Output: 9.26100
Example 3:
Input: 2.00000, -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
- -100.0 < x < 100.0
- n is a 32-bit signed integer, within the range [−231, 231 − 1]
题解:
建立一个helper function返回n为正数时的power, 主函数里分开调用即可。
corner case 当n = Integer.MIN_VALUE, -n会overflow. 所以helper function 用long型.
helper中采用递归,原理就是x^n = x^(n/2) * x^(n/2) * (n == 奇数)*x, 终止条件是n==0时返回一.
Note: calculate half = powPositive(x, n / 2) first to cache extra result.
Time Complexity: O(logn).
Space: O(logn), stack space.
AC Java:
1 class Solution { 2 public double myPow(double x, int n) { 3 if(n<0){ 4 return 1/powPositive(x, -1*(long)n); 5 } 6 7 return powPositive(x, n); 8 } 9 10 private double powPositive(double x, long n){ 11 if(n == 0){ 12 return 1.0; 13 } 14 15 double half = powPositive(x, n/2); 16 if(n%2 == 1){ 17 return half * half * x; 18 }else{ 19 return half * half; 20 } 21 } 22 }
Iterative 方法.
Time Complexity: O(logn).
Space: O(1).
AC Java:
1 class Solution { 2 public double myPow(double x, int n) { 3 long N = (long)n; 4 if(N < 0){ 5 N = -N; 6 x = 1/x; 7 } 8 9 double res = 1; 10 double product = x; 11 for(long i = N; i>0; i/=2){ 12 if(i%2 == 1){ 13 res = res*product; 14 } 15 16 product = product*product; 17 } 18 19 return res; 20 } 21 }
这道题和Sqrt(x)以及Divide Two Integers都是原有公式的题。这类题目一般用二分法.