【剑指Offer 16】数值的整数次方
作者:互联网
/**
* 剑指 Offer 16. 数值的整数次方
* https://leetcode.cn/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/
*
* 思路:快速幂
* x^n = x^a * x^b (n=a+b)
* 13 = 1101 (十进制转二进制)
* x^13 = (1 * x^8) * (1 * x^4) * (0 * x^2) * (1 * x^1) (0 表示不计入结果)
* */
public class Solution {
public double myPow(double x, int n) {
double result = 1.0;
// 将 -n 转成整数处理
double base;
if (n < 0) {
base = 1 / x;
n = -n;
} else {
base = x;
}
// 计算 n 次方
while (n != 0) {
if ((n & 1) == 1) {
result *= base;
}
n = n >>> 1;
base *= base;
}
return result;
}
}
标签:13,Offer,double,16,base,result,次方 来源: https://www.cnblogs.com/liaozibo/p/offer-16.html