题目描述:
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。
示例 1:
输入:x = 2.00000, n = 10
输出:1024.00000
示例 2:
输入:x = 2.10000, n = 3
输出:9.26100
示例 3:
输入:x = 2.00000, n = -2
输出:0.25000
解释:2-2 = 1/22 = 1/4 = 0.25
提示:
-100.0 < x < 100.0
-231 <= n <= 231-1
-104 <= xn <= 104
思路:倒是挺好想的,但是个人经验能不用递归真的不要用递归
不正确!
其实我也不知道我这个为什么不正确。
后来改了改还栈溢出了(eclispe没问题但是力扣栈溢出)崩溃!
代码:
class Solution {
public double myPow(double x, int n) {
DecimalFormat format = new DecimalFormat("#.00000");
if(n<0) {
return 1/myPow(x,0-n);
}else if(n == 0){
return 1.00000;
}else {
if(n==1) return Double.parseDouble(format.format(x));
double ans = myPow(x,n/2);
if(n%2 == 1) {
return Double.parseDouble(format.format(ans*ans*x));
}else {
return Double.parseDouble(format.format(ans*ans));
}
}
}
}
所以先看看那些通过的代码是什么样的。
哎!大佬还是大佬,最近看的这几道题都是同一个大佬精选题解
贴上大佬代码
public static double myPow(double x, int n) {
if(x == 0) return 0;
long b = n;
double res = 1.0;
if(b < 0) {
x = 1 / x;
b = -b;
}
while(b > 0) {
if((b & 1) == 1) res *= x;
x *= x;
b >>= 1;
}
return res;
}