Math的multiplyExact和addExact方法java8

这篇文章是对于我算法训练题里面reverse integer的补充,不想和算法题写在一起所以单独写了出来。

/**
     * 返回根据参数生成的结果,如果结果超过了int的范围,那么就会抛出异常。
     *
     * @param x 第一个值
     * @param y 第二个值
     * @return 结果
     * @throws 超出int范围时抛出ArithmeticException异常
     * @since 1.8
     */
    @HotSpotIntrinsicCandidate
    public static int multiplyExact(int x, int y) {
		//先把x和y强转为long类型,因为long的最大值可以容纳int型。
		//long的最大值9,223,372,036,854,775,807
        long r = (long)x * (long)y;
        if ((int)r != r) {
            throw new ArithmeticException("integer overflow");
        }
        return (int)r;
    }

通过上面源码,我们可以看到,该方法主要是将x与y的值相乘,如果超过int范围就会抛出异常。

/**
     * Returns 返回参数的和,如果参数的和超过int范围就会抛出异常
     * @param x 第一个值
     * @param y 第二个值
     * @return 结果
     * @throws 超出int范围就会抛出异常ArithmeticException 
     * @since 1.8
     */
    @HotSpotIntrinsicCandidate
    public static int addExact(int x, int y) {
        int r = x + y;
        // HD 2-12 Overflow iff both arguments have the opposite sign of the result
        if (((x ^ r) & (y ^ r)) < 0) {
            throw new ArithmeticException("integer overflow");
        }
        return r;
    }

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值