美文网首页
LeetCode每日一题:pow(x,n)

LeetCode每日一题:pow(x,n)

作者: yoshino | 来源:发表于2017-06-14 16:58 被阅读28次

    问题描述

    Implement pow(x, n).

    问题分析

    这一题让我们模拟pow(x,n)函数,下面提供一种二分的方法,时间复杂度为O(logn)

    代码实现

    public double pow(double x, int n) {
            if (n == 0) return 1.0;
            double half = pow(x, n / 2);
            if (n % 2 == 0) {
                return half * half;
            } else if (n > 0) {
                return half * half * x;
            } else {
                return half / x * half;
            }
        }
    

    相关文章

      网友评论

          本文标题:LeetCode每日一题:pow(x,n)

          本文链接:https://www.haomeiwen.com/subject/nnqeqxtx.html