Integer power values: to prove safety offer 13

Title Description

Given a double base type and floating-point type int integer exponent. Seeking exponent of the power base.
Ensure the base and exponent are not simultaneously 0
 

problem analysis

Calculating integer power of a floating point number, mainly on the ability to estimate the integrity of the input data. To solve this problem, the input data may exist if:

1. The base number is not zero, an integer indices

2. The base number is not 0, index are negative

3. The base number is 0, the index is negative (zero situation)

4. The base number is 0, the index is a positive number (given special value 0 or 1)

Logic code implemented is not complicated, the primary need to consider all possible input cases, also be noted that, for the floating-point number, is not directly use the "==" directly comparing two numbers.

C ++ code realization are given below:

class Solution {
public:
    double Power(double base, int exponent) {//排除零除的情况出现
        if(std::abs(base-0.0)<(1e-4) && exponent<0){return 0.0;
        }
        bool isnegative=(exponent<0)? true:false;
        if(isnegative){
          return 1.0/calc_power(base,-exponent);  
        } 
        else{
            return calc_power(base,exponent);  
        }
    }
    double calc_power(double base,int unsignedexp){
        double res=1.0;
        for (int i=0;i<unsignedexp;i++){
            res*=base;
        }
        return res;
    }
     };

 If you want to improve the computational efficiency calc_power function can be implemented using the following recursive method, reduced time complexity O (logn) from O (n), but the complexity of the recursion stack space becomes O (logn)

Double calc_power ( Double  Base , int unsignedexp) {
         // log (n-) time complexity, the same depth of recursion is log (n-) 
        IF (unsignedexp == 0 ) {
             return  1.0 ; 
        } 
        IF (unsignedexp == . 1 ) {
             return  Base ; 
        } 
        Double Result = calc_power ( Base , unsignedexp >> . 1 ); 
        Result * = Result;
         IF ((unsignedexp & 0x1 ) == . 1 ) { 
            Result*=base;
        }
        return result;
    }

 

Guess you like

Origin www.cnblogs.com/fancy-li/p/11613810.html