數值的整數次方16

題目:實現函數double Power(double base, int exponent),求base的exponent次方。不得使用庫函數,同時不需要考慮大數問題。

public static double powerWithExponent(double base, int exponent) {
    if (exponent == 0) {
        return 1;
    }
    if (exponent == 1) {
        return base;
    }

    double result = powerWithExponent(base, exponent >> 1);
    result = result * result;
    if ((exponent & 0x1) == 1) {
        result *= base;
    }
    return result;
}

public static void main(String[] args) {
    System.out.println(powerWithExponent(2, 2));
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章