class Solution {
public double myPow(double x, int n) {
long N = n;
if (N < 0) {
N = -N;
x = 1/x;
}
double res = 1.0;
while (N != 0) {
if ((N&1) != 0)
res *= x;
x *= x;
N >>= 1;
}
return res;
}
}
注:
1. 非递归方式,直接采用位运算作为判断条件。N&1主要用来判断奇偶
2. 这题比较坑的是有一个例子是
Integer.MIN_VALUE= -2147483648
但是
Integer.MAX_VALUE= 2147483647
所以用int无法实现转换,需要把n转成long