【剑指offer】面试题 16. 数值的整数次方

面试题 16. 数值的整数次方


题目描述

    题目:给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

解答过程

下面的讨论中 x 代表 base,n 代表 exponent。




因为 (x*x)n/2 可以通过递归求解,并且每递归一次,n 都减小一半,因此整个算法的时间复杂度为 O(logn)。

代码实现

方法一:

public class Solution {
    public double Power(double x, int n) {
         if(n<0) return 1/x * Power(1/x, -(n+1));
         if(n==0) return 1;
         if(n==2) return x*x;
         if(n%2==0) return Power( Power(x, n/2), 2);
         else return x*Power( Power(x, n/2), 2);
    }
}

方法二:

public class Solution {
    public double Power(double x, int n) {
        if(n==0) return 1;
        if(n<0){
            n = -n;
            x = 1/x;
        }
        return n%2==0 ? Power(x*x, n/2) : x*Power(x*x, n/2);
    }
}

猜你喜欢

转载自www.cnblogs.com/hglibin/p/9030136.html
今日推荐