12数值的整数次方
题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
思路:
使用递归,时间复杂度O(logn)
- 当n为偶数,a^n =(a^n/2)*(a^n/2)
- 当n为奇数,a^n = a^[(n-1)/2] * a^[(n-1)/2] * a
1 public class Solution { 2 public double Power(double base, int exponent) { 3 if(exponent==1) return base; 4 if(exponent==-1) return 1/base; 5 if(exponent==0) return 1; 6 double res = Power(base,exponent>>1); 7 return (exponent &0x01)==0? res*res:base*res*res; 8 } 9 }
c++:20180807
1 class Solution { 2 public: 3 double Power(double base, int exponent) { 4 if(exponent==1) return base; 5 if(exponent==-1) return 1/base; 6 if(exponent==0) return 1; 7 double res = Power(base,exponent>>1); 8 if(exponent &1) return res*res*base; 9 else return res*res; 10 } 11 };