Leetcode::pow
1 class Solution { 2 public: 3 bool equal( double a,double b ) 4 { 5 if( a-b < 0.0000001 && a-b > -0.0000001 ) 6 { 7 return true; 8 } 9 else 10 { 11 return false; 12 } 13 } 14 15 double pow_unsigned(double x,unsigned int n ) 16 { 17 if( n == 0 ) 18 return 1; 19 if( n== 1 ) 20 return x; 21 22 double result=pow_unsigned(x,n>>1); 23 result*=result; 24 if( n & 1 == 1) 25 result*=x; 26 return result; 27 } 28 double pow(double x, int n) { 29 // Start typing your C/C++ solution below 30 // DO NOT write int main() function 31 if( equal(x,0) && n <0 ) 32 { 33 return 0.0; 34 } 35 36 unsigned int t_n=(unsigned int)n; 37 38 if(n<0) 39 t_n=(unsigned int)(-n); 40 41 double result=pow_unsigned(x,t_n); 42 43 if(n<0) 44 result=1.0/result; 45 46 return result; 47 48 } 49 };
由于考虑到double、float类型数的精度,equal函数来判断是否等于0,当然直接==判断也行;
时间复杂度为O(logn);