码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Pow(x, n) 求x的n次方

时间:2016-07-18 02:31:51      阅读:203      评论: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

 

LeetCode上的原题,请参见我之前的博客Pow(x, n)

 

解法一:

class Solution {
public:
    /**
     * @param x the base number
     * @param n the power number
     * @return the result
     */
    double myPow(double x, int n) {
        if (n == 0) return 1;
        double half = myPow(x, n / 2);
        if (n % 2 == 0) return half * half;
        else if (n > 0) return half * half * x;
        else return half * half / x;
    }
};

 

解法二:

class Solution {
public:
    /**
     * @param x the base number
     * @param n the power number
     * @return the result
     */
    double myPow(double x, int n) {
        if (n == 0) return 0;
        if (n == 1) return x;
        if (n == -1) return 1 / x;
        return myPow(x, n / 2) * myPow(x, n - n / 2);
    }
};

 

[LintCode] Pow(x, n) 求x的n次方

标签:

原文地址:http://www.cnblogs.com/grandyang/p/5679800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!