The sword refers to offer---the integer power of the value

The sword refers to offer—the integer power of the value

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

The code in the blog is passed in Nioke C++11 (clang++ 3.9)

This question is actually a simulated implementation of the pow function in the C library. At first glance, you may think this question is very simple, but it should be noted that we need to consider the case where the exponent is not a positive number.
Generally speaking, the 0-th power of 0 is It is meaningless, but in advanced mathematics, its positive convergence tends to be close to 1. Here, it
is illegal to treat the negative power of 0 according to 1, because the negative power is equivalent to taking the reciprocal of its absolute value power. And 0 cannot be used as the denominator. We can feedback this situation through return values, global variables and exceptions. When global variables
are used here, we may solve the problem through exponent-1 loops. In fact, we can change our way of thinking: for example, to ask for the 16th power, You can find the 8th power first, and the 8th power first, and then the 4th power... In this way, we can do a lot of multiplications less. Here, through the recursive method, each time the exponent is shifted to the right, and for the recursive layer where the exponent is an odd number Need to multiply base again

code show as below:

bool InvalidInput = false;
class Solution {
    
    
public:
    double Power(double base, int exponent) {
    
    
        if(0.0 == base && exponent<0)
        {
    
    
            InvalidInput = true;
            return 0.0;
        }
        
        unsigned int x = (unsigned int)exponent;
        if(exponent<0)
            x = (unsigned int)(-exponent);
        double ret = Power1(base,x);
        if(exponent<0)
            ret = 1.0/ret;
        return ret;
    }
    
private:
    double Power1(double base, int exponent)
    {
    
    
        if(0 == exponent)
            return 1;
        if(1 == exponent)
            return base;
        
        double ret = Power1(base,exponent>>1);
        ret *= ret;
        if(1 == (exponent&0x1)) //这里注意按位与运算的优先级比==低,所以加括号
            ret *= base;
        return ret;
    }
};

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324064947&siteId=291194637