The sword refers to the integer power of offer-12-value--Java implementation

topic

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

Make sure that base and exponent are not 0 at the same time

analyze

Idea one:

insert image description here

Code:

public class Solution {
    
    
    public double Power(double base, int exponent) {
    
    
        double res = 1;
        int curExp;
        if(exponent > 0) {
    
    
            curExp = exponent;
        } else if (exponent < 0) {
    
    
            if(base == 0) {
    
    
                throw new RuntimeException("基数不能为0");
            }
            curExp = -exponent;
        } else {
    
    
            return 1;
        }
        
        while(curExp != 0) {
    
    
            if((curExp & 1) == 1) {
    
    
                res *= base;
            }
            base *= base;//翻倍
            curExp >>= 1;
        }
        
        return exponent > 0 ? res : (1/res);
  }
}

Guess you like

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