实现 pow(x,n)
注意事项
不用担心精度,当答案和标准输出差绝对值小于1e-3
时都算正确
Pow(2.1, 3) = 9.261
Pow(0, 1) = 0
Pow(1, 0) = 1
思路:迭代的解法,让i初始化为n,然后看i是否是2的倍数,是的话x乘以自己,否则res乘以x,i每次循环缩小一半,直到为0停止循环。最后看n的正负,如果为负,返回其倒数
class Solution {
public:
/**
* @param x the base number
* @param n the power number
* @return the result
*/
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;
}
};