Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};
posted on 2014-08-01 05:09  Tonix  阅读(151)  评论(0编辑  收藏  举报