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

LeetCode "Pow(x,n)"

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

标签:style   blog   color   io   for   ar   div   log   

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)"

标签:style   blog   color   io   for   ar   div   log   

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

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