Implement pow(x, n).
直接计算会超时TLE
1 public double pow(double x, int n) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 if(n == 0) 5 return 1; 6 7 double result = 1; 8 if(n > 0){ 9 while(n > 0){ 10 result *= x; 11 n --; 12 } 13 } else { 14 while(n < 0){ 15 result /= x; 16 n ++; 17 } 18 } 19 return result; 20 } 21 22 // TLE test case 23 0.00001, 2147483647
使用二分法来求解,O(lgn)
这里需要注意的是当n = -2147483648,0-n=-2147483648 即整数的整数范围最大为:-2147483648~2147483647
这里需要把int 提升为long
1 public class Solution { 2 public double pow(double x, int n) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 long tmp = n; 6 if(tmp >= 0){ 7 return power(x, tmp); 8 } else { 9 return 1.0 / power(x, -tmp); 10 } 11 } 12 13 public double power(double x, long n){ 14 if(n == 0) 15 return 1; 16 17 if(n == 1) 18 return x; 19 20 double result = power(x, n >> 1); 21 result *= result; 22 if((n & 0x1) == 1){ 23 result = result * x; 24 } 25 26 return result; 27 } 28 }