1. 程式人生 > >數值的整數次方 java

數值的整數次方 java

數值的整數次方 java

題目描述
給定一個double型別的浮點數base和int型別的整數exponent。求base的exponent次方。

程式碼1:

public class Solution {
    public double Power(double base, int exponent) {
        double a = 1.0;
        if(exponent == 0){
            a = 1;
        }
        if(exponent > 0){
            for(int i = 0; i < exponent; i++){
                a = a * base;
            }
        }
        if(exponent < 0){
            exponent = - exponent;
            for(int i = 0; i < exponent; i++){
                a = a * base;
            }
            a = 1 / a;
        }
        return a;
    }
}

程式碼2:推薦

public class Solution {
    public double Power(double base, int exponent) {
        double a = 1.0;
        if(exponent == 0){
            a = 1;
        }
        if(exponent > 0 || exponent < 0){
            for(int i = 0; i < exponent || i < - exponent; i++){
                a = a * base;
            }
            if(exponent < 0){
                a = 1 / a;
            }
        }
        return a;
    }
}