这篇文章是对于我算法训练题里面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;
}