题目:实现函数double Power(x, n),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
分析:直接计算,这里要考虑n为负数的情况。或者采用递归的方法。
递归其实非常简单,首先要写出递归中止的条件,然后写递归即可。递归就像弹簧一样,一直压东西进去(栈),而后压到不能动(碰到中止条件了),而后从最内层开始反弹,直到整个弹簧回复。
class Solution {
public double myPow(double x, int n) {
//来一手递归
if(n==0) return 1.0;
if(n==1) return x;
if(n==-1) return 1/x;//先写出递归中止的条件
if(n%2==0){
double t=myPow(x,n/2);//递归
return t*t;
}else{
double t=myPow(x,n/2);//递归
if (n < 0) x = (1 / x);
return t * t * x;
}
}
}
用到递归的思想的回溯、DFS等挺多的,其实很简单一个套路,先写中止条件,然后递归完事。hhh
下面是直接计算的方法:
class Solution {
public double myPow(double x, int n) {
if(x == 0) return 0;
long b = n;//要考虑大数的情况
double res = 1.0;
if(b < 0) {//这里需要主要b<0的时候,因为pow时候乘的是1/x
x = 1 / x;
b = -b;
}
while(b > 0) {
if((b & 1) == 1) res *= x;
x *= x;
b >>= 1;
}
return res;
}
}