首页 > 其他 > 详细

数值的整数次方

时间:2019-04-27 23:40:34      阅读:172      评论:0      收藏:0      [点我收藏+]

原文地址:https://www.jianshu.com/p/d2f647a1e073
时间限制:1秒 空间限制:32768K

题目描述

给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。

我的代码

class Solution {
public:
    double Power(double base, int exponent) {
        int flag=1;
        if(exponent<0){
            flag=0;
            exponent=-exponent;
        }
        if(base==0)
            if(exponent<=0)
                throw base;
        if(exponent==0)
            return 1;
        double res=1.0;
        while(exponent--){
            res*=base;
        }
        return flag>0?res:1/res;
    }
};

运行时间:4ms
占用内存:384k

class Solution {
public:
    double Power(double base, int exponent) {
        double res=1.0;
        int n;
        if(exponent<0){
           n=-exponent;
           if(base==0)
               throw base;
        }
        else if(exponent==0){
            if(base==0)
                throw base;
            return 1;
        }
        else
            n=exponent;
        while(n){
            if((n&1)==1)
                res*=base;
            base=base*base;
            n>>=1;
        }
        return (exponent>0)?res:1/res;
    }
};

运行时间:5ms
占用内存:508k

数值的整数次方

原文:https://www.cnblogs.com/cherrychenlee/p/10780944.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!