11 Integer power of numerical value

Given a float base of type double and an integer exponent of type int. Find the exponent power of base.

 

For example, to find the 32nd power of 2, first find the 16th power of 2, then 2^16 * 2^16
and then recursively find 2^16, if the power is odd, then multiply by a base

 

 

C++:

 1 class Solution {
 2 private:
 3     bool invalidInput = false ;
 4 public:
 5     bool Equal(double num1 , double num2){
 6         if ((num1-num2)<0.0000001 && (num1-num2)>-0.0000001)
 7             return true ;
 8         else
 9             return false ;
10     }
11 
12     double PowerWithUnsignedExponent(double base , int exponent){
13         if (exponent == 0)
14             return 1 ;
15         if (exponent == 1)
16             return base ;
17         double result = PowerWithUnsignedExponent(base,exponent>>1) ;
18         result *=result ;
19         if (exponent&1)
20             result *= base ;
21         return result ;
22     }
23 
24     double Power(double base , int exponent){
25         bool invalidInput = false ;
26         if (Equal(base,0.0) && exponent < 0){
27             invalidInput = true ;
28             return 0.0 ;
29         }
30         int absExponent = abs(exponent) ;
31         double result = PowerWithUnsignedExponent(base,absExponent) ;
32         if (exponent < 0)
33             result = 1.0/result ;
34         return result ;
35     }
36 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324777534&siteId=291194637