实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。
class Solution {
public double myPow(double x, int n) {
if(x == 0){
return 0;
}
double res = 1.0;
long b = n;
if(b < 0){
x = 1/x;
b = -b;
}
while(b > 0){
//如果为奇数
if((b&1) == 1){
res *= x;
}
x *= x;
b >>= 1;
}
return res;
}
}
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:40.8 MB, 在所有 Java 提交中击败了15.96%的用户
通过测试用例:304 / 304