Pow(x, n)
问题:
Implement pow(x, n).
思路:
分治法
我的代码:
public class Solution { public double pow(double x, int n) { return n >= 0 ? helper(x,n) : 1/helper(x,-1*n); } public double helper(double x, int n) { if(n == 0) return 1; if(n == 1) return x; double left = helper(x, n/2); return n%2==0? left*left : left*left*x; } }
他人代码:
class Solution { public double pow(double x, int n) { double res=1; if(n<0){ x=1/x; n=-n; } while(n>0){ if(n&1==1){ res=res*x; } x*=x; n=n>>1; } return res; } };
学习之处:
位操作不明觉厉