The sword refers to offer-12: 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.

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

Thought analysis

  • Pay attention to boundary judgment
  • If it is 0, return directly
  • If the exponent is negative, it needs to be calculated with base as the denominator

Code

public class Solution {
    
    
    public double Power(double base, int exponent) {
    
    
        double res = 1;
        if (exponent == 0) {
    
    
            return 1;
        } else if (exponent < 0) {
    
    
            while (exponent ++ < 0) {
    
    
                res *= (1 / base);
            }
        } else if (exponent > 0) {
    
    
            while (exponent-- > 0) {
    
    
                res *= base;
            }
        }
        return res;
  }
}

Guess you like

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