Pow(x,y)
做题博客链接
https://blog.csdn.net/qq_43349112/article/details/108542248
题目链接
https://leetcode-cn.com/problems/powx-n/
描述
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。
提示:
-100.0 < x < 100.0
-231 <= n <= 231-1
-104 <= xn <= 104
示例
示例 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
初始代码模板
class Solution {
public double myPow(double x, int n) {
}
}
代码
class Solution {
public double myPow(double x, int n) {
if (x == 0.0) {
return 0.0;
}
double res = 1.0;
long b = n;
if (n < 0) {
x = 1 / x;
b = -b;
}
while (b > 0) {
if ((b & 1) == 1) res *= x;
x *= x;
b >>= 1;
}
return res;
}
}