50. Pow(x, n)
Implement pow(x, n).
example1
Input: 2.00000, 10
Output: 1024.00000
example2
Input: 2.10000, 3
Output: 9.26100
这道题要我实现pow(x,n)这个函数,也就是x的n次方的计算。
class Solution {
public:
double myPow(double x, int n) {
double ans = 1;
unsigned long long p;
if (n < 0) { //负数次方将其转化为分数的正数次方
p = -n;
x = 1 / x;
} else {
p = n;
}
while (p) {
if (p & 1)
ans *= x;
x *= x;
p >>= 1;
}
return ans;
}
};