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

转载于:https://www.cnblogs.com/panini/p/6718252.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值