题目:
Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10
Output: 1024.00000
Example 2:
Input: 2.10000, 3
Output: 9.26100
Example 3:
Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25
Note:
-100.0 < x < 100.0
n is a 32-bit signed integer, within the range [−231, 231 − 1]
解法1:
递归法 二分法
递归基 n == 0,返回0
递归得到n折半的结果为v,如果n为偶数,最终的结果为v * v
如果n为奇数,还需要乘个x
最后考虑负数,负数直接考虑整数的结果,然后求倒数即可
但是考虑整数最小值没有对应的正数,所以我们要特判输出0,但是在此之前要考虑1和-1的情况,1的任何次方为1,-1的偶数次方为1,奇数次方为-1
c++:
class Solution {
public:
double myPow(double x, int n) {
if(x == -1.0){
if(n % 2 == 0) return 1.0;
else return -1.0;
}
if(x == 1.0) return 1.0;
if(n == INT_MIN) return 0;
if(n < 0) return 1.0 / power(x, -n);
else return power(x, n);
}
double power(double x, int n) {
if(n == 0) return 1;
double v = power(x, n / 2);
if(n % 2 == 0) return v * v;
else return v * v * x;
}
};
java:
class Solution {
public double myPow(double x, int n) {
if(x == -1.0){
if(n % 2 == 0) return 1.0;
else return -1.0;
}
if(x == 1.0) return 1.0;
if(n == Integer.MIN_VALUE) return 0;
if(n < 0) return 1.0 / power(x, -n);
else return power(x, n);
}
private double power(double x, int n) {
if(n == 0) return 1;
double v = power(x, n / 2);
if(n % 2 == 0) return v * v;
else return v * v * x;
}
}
python:
python没有溢出问题不用考虑特判
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
# if x == -1.0:
# if n % 2 == 0: return 1.0
# else: return -1.0
# if x == 1.0: return 1.0
if n < 0: return 1.0 / self.power(x, -n)
else: return self.power(x, n)
def power(self,x, n):
if n == 0: return 1
v = self.power(x, n / 2)
if n % 2 == 0: return v * v
else: return v * v * x
解法2:
迭代法
参考解法三 迭代
n以2进制的表示,如x的10次方,10二进制为1010,即我们乘以二进制位为1的位即可,我们从右往左迭代,首先乘以第二位的*21,然后乘以第4位的23
程序从右往左依次遍历二进制位,为1的话,更新结果,无论是不是1,都要更新相乘的系数
c++:
class Solution {
public:
double myPow(double x, int n) {
if(x == -1.0){
if(n % 2 == 0) return 1.0;
else return -1.0;
}
if(x == 1.0) return 1.0;
if(n == INT_MIN) return 0;
double res = 1.0;
int absn = n < 0 ? -n : n;
for(int i = absn; i > 0; i /= 2){
if(i % 2 == 1) res *= x;
x *= x;
}
return n < 0 ? 1.0 / res : res;
}
};
java:
class Solution {
public double myPow(double x, int n) {
if(x == -1.0){
if(n % 2 == 0) return 1.0;
else return -1.0;
}
if(x == 1.0) return 1.0;
if(n == Integer.MIN_VALUE) return 0;
double res = 1.0;
int absn = n < 0 ? -n : n;
for(int i = absn; i > 0; i /= 2){
if(i % 2 == 1) res *= x;
x *= x;
}
return n < 0 ? 1.0 / res : res;
}
}
python:
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
res = 1.0
absn = -n if n < 0 else n
while absn > 0:
if absn % 2 == 1: res *= x
x *= x
absn /= 2
return 1.0 / res if n < 0 else res