数值的整数次方

题目

实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。

分析

在这里插入图片描述

代码实现
public class Solution {

    public static void main(String[] args) {
        Solution15 s = new Solution15();
        System.out.println(s.Power(2.00000, -2147483648));

    }
    /**
     *  数值的整数次方
     * @param base  底数
     * @param exponent 指数
     * @return
     */
    public double Power(double base, int exponent) {
        //主要是解决-2147483648的绝对值问题,
        //long e = Math.abs((long)exponent);
        if (base == 0 && exponent < 0){
            return 1/base;//正无穷
        }
        double res = 1;
        for (int i = 0; i < Math.abs(exponent); i++){
            res *= base;
        }
        if (exponent < 0){
            res = 1 / res;
        }
        return res;
    }
}
分析

在这里插入图片描述

代码实现
public class Solution {

    public static void main(String[] args) {
        Solution15 s = new Solution15();
        System.out.println(s.Power(2.00000, -2147483648));
    }

    /**
     *  数值的整数次方
     * @param x  底数
     * @param n 指数
     * @return
     */
    public double Power(double x, int n) {
        long e = Math.abs((long)n);
        double res = mutiply(x, e);
        if (n < 0){
            res = 1/res;
        }
        return res;
    }

    public  double mutiply(double x, long n) {
        if (n == 0){
            return 1;
        }
        if (n == 1){
            return x;
        }
        double res = mutiply(x,n/2);
        res *= res;
        if (n % 2 == 1){
            res *= x;
        }
        return res;
    }

}
分析

在这里插入图片描述

代码
public class Solution {

    public static void main(String[] args) {
        Solution15 s = new Solution15();
        System.out.println(s.myPower(2.00000, -2147483648));
    }

    /**
     * 数值的整数次方
     * @param x  底数
     * @param n 指数
     * @return
     */
    public double myPower(double x, int n) {
        if (x == 0){
            return 0;
        }
        long e = Math.abs((long)n);
        double res = 1;
        while (e > 0){
            //判断最后一位 如果是1 则表明bm为1 则2的次方有作用
            if ((e & 1) == 1){
                res *= x;
            }
            x *= x;
            //右移一位
            e >>= 1;
        }
        if (n < 0){
            res = 1 / res;
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值