Pow(x, n)

Implement pow(xn).

很有趣的题,第一次暴力乘了,超时。然后就想到多项式分解了,想到二进制,想到了取次数相当于二进制遇“0”不管,遇“1”乘x,移位取平方。

代码测试后出现负次数没有过,加了这部分代码就过了。

代码不难,优化只需要小动脑,还是挺好玩的。

class Solution {
public:
    double pow(double x, int n) {
        double result =1;
        int flag = 0;
        if(n<0)flag =1;
        n= abs(n);
        stack<int> sk;
        while(n>0)
        {
            sk.push(n%2);
            n = n/2;
        }
        while(!sk.empty())
        {
            result *= result;
            if(sk.top() == 1) result *= x;
            sk.pop();
        }
        if(flag ==1)
        result =1/result;
        return result;
    }
};

  

posted on 2014-03-11 22:13  pengyu2003  阅读(119)  评论(0编辑  收藏  举报

导航