Niuke.com's sword refers to Offer - the integer power of the value

Topic description

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

Problem solving ideas

The practice of this question is relatively simple, but there are many points to pay attention to:

1. When the base is 0: When judging whether the base is 0, you also need to pay attention. Since the computer indicates that decimals (including float and double decimals) have errors, you cannot directly use == to judge whether two decimals are equal. If two decimals are equal The absolute value of the difference of decimals is very small, such as less than 0.0000001, they can be considered equal.

2. When the exponent is a negative number : when the exponent is a negative number, you can first calculate the absolute value of the exponent , then calculate the result of the power and then take the reciprocal

code

class Solution {
public:
    double Power(double base, int exponent) {
        if( abs(base-0.0) < 0.0000001 )
            return 0;
        if( exponent == 0 )
            return 1;
        if( exponent == 1 )
            return base;
        
        unsigned int absExponent = (unsigned int) exponent;
        if( exponent < 0 )
            absExponent = (unsigned int) (-exponent);
        
        double res = 1.0;
        for( int i=0;i<absExponent;i++ )
            res *= base;
        
        if( exponent < 0 )
            res = 1.0 / res;
        
        return res;
    }
};

optimization

The complexity of the above method is O(n), of course there is a slightly better solution: 
when n is even, base^n = base^(n/2) * base^(n/2) 
when n is even base^n = base^(n/2) * base^(n/2) *base

In this way, the size of (n/2) can be calculated recursively, and finally, it is only necessary to judge the parity row of the incoming expont and perform one more operation. In this case, the complexity is O(logn).

class Solution {
public:
    double Power(double base, int exponent) {
        if( abs(base-0.0) < 0.0000001 )
            return 0;
        if( exponent == 0 )
            return 1;
        if( exponent == 1 )
            return base;
        
        double res = 1.0;
        unsigned int absExponent = (unsigned int) exponent;  
        if( exponent < 0 )  
            absExponent = (unsigned int) (-exponent);
        
        res = Power( base, absExponent>>1 );
        res * = res;
        if( absExponent & 1 )
            res *= base;
        
        if( exponent < 0 )
            res = 1 / res;
        
        return res;
    }
};

Guess you like

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