实现 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/powx-n
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一(耗时长):
import java.util.Formatter;
import java.util.Scanner;
public class Test8 {
public static void main(String[]args){
Scanner scanner = new Scanner(System.in);
System.out.print("输入x=");
double x = scanner.nextDouble();
System.out.print("输入n=");
int n = scanner.nextInt();
pow r = new pow();
System.out.println("输出:"+String.format("%.5f",r.mypow(x,n)));
}
}
class pow{
public double mypow(double x,int n){
x = x;
n = n;
double k =x;
if(n>=0){
if (n>0){
for (int i = 0;i<n-1;i++){
x*=k;
}
return x;
}
else return 1;
}
else{
x=1.0/x;
k=x;
for (int i=n;i<0-1;i++){
x*=k;
}
return x;
}
}
}
解法二(leetcode评论区大神思路,耗时巨短):
class Solution {
public double myPow(double x, int n) {
double res = 1.0;
for(int i = n; i != 0; i /= 2){
if(i % 2 != 0){
res *= x;
}
x *= x;
}
return n < 0 ? 1 / res : res;
}
}
运行结果: