LeetCode 数值的整数次方 [中等]
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.10000, 3
输出: 9.26100
示例 3:
输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25
题目分析
解法1
使用递归实现 不停的进行取模除2,然后返回结果
解法2
都转换为正次幂进行求解
我解释不清楚 直接放链接了:https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/solution/mian-shi-ti-16-shu-zhi-de-zheng-shu-ci-fang-kuai-s/
代码实现
public class MyPow {
public static void main(String[] args) {
System.out.println(myPow2(34.00515, -3));
System.out.println(myPow2(2.0000, -2));
System.out.println(myPow3(34.00515, -3));
System.out.println(myPow3(2.0000, -2));
}
public static double myPow3(double x, int n) {
if (x == 0) {
return 1;
}
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;
}
public static double myPow2(double x, int n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return x;
}
if (n == -1) {
return 1 / x;
}
double half = myPow2(x, n / 2);
double mod = myPow2(x, n % 2);
return half * half * mod;
}
}
网友评论