剑指 Offer 16. 数值的整数次方

剑指 Offer 16. 数值的整数次方

快速幂

因为n<0时,n可能会等于-2147483648,这时候n=-n就会溢出,简单的方式就是转换成long long

class Solution {
public:
    double myPow(double x, int n) {
        long long tn=n;
        double res=1;
        if(n>0){
            while(n){
                if(n&1)res*=x;
                n>>=1;
                x*=x;
            }
            return res;
        }
        else if(tn<0){
            tn=-tn;
            while(tn){
                if(tn&1)res*=x;
                tn>>=1;
                x*=x;
            }
            return 1.0/res;
        }
        else return 1;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容