首页 > 其他 > 详细

lintcode-medium-Pow(x, n)

时间:2016-04-04 16:07:54      阅读:280      评论:0      收藏:0      [点我收藏+]

Implement pow(x, n).

 

 Notice

You don‘t need to care about the precision of your answer, it‘s acceptable if the expected answer and your answer ‘s difference is smaller than 1e-3.

Example
Pow(2.1, 3) = 9.261
Pow(0, 1) = 0
Pow(1, 0) = 1
Challenge

O(logn) time

 

public class Solution {
    /**
     * @param x the base number
     * @param n the power number
     * @return the result
     */
    public double myPow(double x, int n) {
        // Write your code here
        
        if(n == 0)
            return 1;
        if(n == 1)
            return x;

        if(n > 1){
            if(n % 2 == 0){
                double temp = myPow(x, n / 2);
                return temp * temp;
            }
            else{
                return myPow(x, n - 1) * x;
            }
        }
        else{
            return 1 / myPow(x, -n);
        }
    }
}

 

lintcode-medium-Pow(x, n)

原文:http://www.cnblogs.com/goblinengineer/p/5352027.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!