50. Pow(x, n)

题目:

Implement pow(xn).

链接: http://leetcode.com/problems/powx-n/

题解:

使用二分法求实数幂,假如不建立临时变量halfPow,直接return计算结果的话会超时,还没仔细研究为什么。  

4/15/2017

22ms, 50%

要考虑到n < 0的情况,对输入要确定范围。

另外一种方法是,在第二次判断是n < 0? 1 / (ret * x),但是有精度问题,(34.000515, -3)就会报错。

public class Solution {
    public double myPow(double x, int n) {
        if (n == 0) return 1;

        double temp = myPow(x, n / 2);
        double ret = temp * temp;
        return n % 2 == 0? ret: n < 0? ret / x: ret * x;
    }
}

别人有用位运算做的

https://discuss.leetcode.com/topic/3636/my-answer-using-bit-operation-c-implementation

https://discuss.leetcode.com/topic/40546/iterative-log-n-solution-with-clear-explanation

 1 public class Solution {
 2     public double MyPow(double x, int n) {
 3         double ans = 1;
 4         long absN = Math.Abs((long)n);
 5         while(absN > 0) {
 6             if((absN&1)==1) ans *= x;
 7             absN >>= 1;
 8             x *= x;
 9         }
10         return n < 0 ?  1/ans : ans;
11     }
12 }

更多讨论

https://discuss.leetcode.com/category/58/pow-x-n

posted @ 2017-04-16 11:22  panini  阅读(157)  评论(0编辑  收藏  举报