题目:
数值范围:
拿着这道题啊,不要多说话上来就是判断一下正负,然后x**n
public double myPow(double x, int n) {
if (n == 0) {
return 1.0f;
}
boolean tag = n < 0;
n = Math.abs(n);
double temp = x;
for (int i = 1; i < n; i++) {
x *= temp;
}
return tag ? 1 / x : x;
}
很明显啊O(n)了,直接超时,好了,是时候打开题解,康康大佬们怎么做的,嘿嘿🤭,直接上代码!!!
public static double myPow(double x, int n) {
// 等于0就直接返回0, ok吧
if (x == 0) {
return 0;
}
// 排除0任何数的0次方等于1
if (n == 0) {
return 1.0f;
}
// 将n赋值给long型变量, int 4个字节, 范围在[−2147483648,2147483647]
// 如果为int时, n为-2147483648, 取正数, 越界
long temp = n;
// n 为负数, x = 1 / x, n = -n
if (temp < 0) {
x = 1 / x;
temp = -temp;
}
double result = 1.0f;
while (temp > 0) {
// 当n的最后一位为1时, 赋值
if ((temp & 1) == 1) {
result *= x;
}
x *= x;
// 将n右移一位
temp >>= 1;
}
return result;
}
总体的思路就是:
- 每次让x *= x,将n进行降幂,直到n<=0,
- 设置返回值为result,当n为奇数时,初始值为result * x,
- 每次n为奇数时,将result更新,每次并且将n右移一位