leetcode-剑指16-OK

// language C with STL(C++)
// 剑指16
// https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/
// 同主站50
// https://leetcode-cn.com/problems/powx-n/

class Solution {
public:
    double myPow(double x, int n){
        if(x==0)
            return 0.;
        if( (n ==0) ||(x ==1.0))
            return 1.;

        long nn=n;
        if(n<=0){
            x = 1/x;
            nn = -nn;
        }
        bool ok[33];
        for(int i = 0; i<33; i++)
            ok[i] = false;
        int i = 1;
        while((i<33) && ( nn!=0)){
            if(nn%2 ==1)
                ok[i] = true;
            i++;
            nn /=2;
        }
        double res[33];
        res[0] = 1;
        res[1] = x;
        for(i =2; i<33; i++)
            res[i] = res[i-1]*res[i-1];
        for(i =1 ; i<33; i++){
            if(ok[i])
                res[0] *=res[i];
        }
        return res[0];
    }
};
posted @ 2021-02-06 04:08  RougeBW  阅读(27)  评论(0编辑  收藏  举报