剑指 Offer 16. 数值的整数次方
难度中等114
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
- x^n = x^(n/2) * x^(n/2) 如果n奇数再乘一个x
 判断基数为0的情况
x=0,n<0,return 1/myPowUnsigned(x,-n);会有除零错误
class Solution {public double myPow(double x, int n) {if(x==0)return 1;if(n==0)return 1;if(n==1)return x;if(n>0) {return myPowUnsigned(x,n);} else {return 1/myPowUnsigned(x,-n);}}public double myPowUnsigned(double x,int n) {if(n==0)return 1;if(n==1)return x;double res = myPowUnsigned(x,n/2);res = res * res;if((n&1)==1) {res = res * x;}return res;}}
7. 整数反转
- 判断溢出的方法值得学习
 

class Solution {public int reverse(int x) {while(x!=0 && x%10==0) {x = x/10;}int r = 0;while(x!=0) {int p = x%10;x = x/10;if(r>Integer.MAX_VALUE/10 || (r==Integer.MAX_VALUE && p>7)) return 0;if(r<Integer.MIN_VALUE/10 || (r==Integer.MIN_VALUE && p<-8)) return 0;r = r * 10 + p;}return r;}}
