美文网首页
50. Pow(x, n)

50. Pow(x, n)

作者: a_void | 来源:发表于2016-09-06 12:41 被阅读0次

Implement pow(x, n).

some consideration:

  • what if n < 0
  • avoid recompute
class Solution {
public:
    double myPow(double x, int n) {
        if(0 == n) return 1;
        else if(1 == n) return x;
        else if(-1 == n) return 1 / x;
        else{
            double t = myPow(x, n/2);
            if(n % 2 == 0) return t * t;
            else{
                if(n > 0)return t * t * x;
                else return t * t / x;
            } 
        }
    }
};

相关文章

网友评论

      本文标题:50. Pow(x, n)

      本文链接:https://www.haomeiwen.com/subject/jwedettx.html