首页 > 其他 > 详细

LeetCode "Pow(x,n)"

时间:2014-08-01 06:57:01      阅读:352      评论:0      收藏:0      [点我收藏+]

Next time you see a numeric problem has a too straightforward solution, think about optimized one. 

Like this one: recursion\iteration is tooo slow. So Dichotomy, like sqrt(). Take care of minux n case.

class Solution {
public:
    double pow(double x, int n) {
      if(n == 0)  return 1;
      bool bNeg = false;
      if(n < 0)
      {
        bNeg = true;
        n *= -1;
      }
      
      double r = pow(x, n/2);
      if(n % 2 == 0) r *= r;
      else              r *=r * x;
      
      if(!bNeg) return r;
      else return 1.0/r;
    }
};

LeetCode "Pow(x,n)",布布扣,bubuko.com

LeetCode "Pow(x,n)"

原文:http://www.cnblogs.com/tonix/p/3884032.html

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