首页 > 代码库 > LeetCode "Pow(x,n)"

LeetCode "Pow(x,n)"

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;    }};