Sword refers to offer to brush questions-GZ12-the integer power of the value

Title description:

Given a floating-point base of type double and an integer exponent of type int. Find the exponent power of base.

Ensure that base and exponent are not 0 at the same time
Example 1
input

2,3

return value

8.00000

Violent solution:

public class Solution {
    
    
    public double Power(double base, int exponent) {
    
    
        //暴力解法:时间复杂度o(n),空间复杂度o(1)
        if(base == 0 && exponent == 0){
    
    
            return 0d;
        }
        if(exponent < 0){
    
    
            base = 1/base;
            exponent = - exponent;
        }
        double res = 1;
        for(int i = 1; i <= exponent; i++){
    
    
            res = res*base;
        }
        return res;
  }
}

Non-recursive fast power method

public class Solution {
    
    
    public double Power(double base, int exponent){
    
    
        
        /**
         *1.全面考察指数的正负、底数是否为零等情况。
         *2.写出指数的二进制表达,例如13表达为二进制1101。
         *3.举例:10^1101 = 10^0001*10^0100*10^1000。
         *4.通过&1和>>1来逐位读取1101,为1时将该位代表的乘数累乘到最终结果。
         */
        if(base == 0 && exponent == 0){
    
    
            return 0d;
        }
        if(exponent < 0){
    
    
            base = 1/base;
            exponent = -exponent;
        }
        double res = 1;
        while(exponent != 0){
    
    
            if((exponent&1) == 1){
    
    //表名这一位有1,可以进行累乘
                res = res * base;
            }
            base = base*base;
            exponent>>=1;//右移一位
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/weixin_42118981/article/details/112689866