java 加法 溢出_StackOverflow热帖:Java整数相加溢出怎么办?Java8一步搞定~
閱讀本文大概需要 2 分鐘。
作者:Aaron_濤
問題
在之前刷題的時候遇見一個問題,需要解決int相加后怎么判斷是否溢出,如果溢出就返回Integer.MAX_VALUE
解決方案
JDK8已經幫我們實現了Math下,不得不說這個方法是在StackOverflow找到了的,確實比國內一些論壇好多了~
加法
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;
}
減法
public static int subtractExact(int x, int y) {
int r = x - y;
// HD 2-12 Overflow iff the arguments have different signs and
// the sign of the result is different than the sign of x
if (((x ^ y) & (x ^ r)) < 0) {
throw new ArithmeticException("integer overflow");
}
return r;
}
乘法
public static int multiplyExact(int x, int y) {
long r = (long)x * (long)y;
if ((int)r != r) {
throw new ArithmeticException("integer overflow");
}
return (int)r;
}
注意 long和int是不一樣的
public static long multiplyExact(long x, long y) {
long r = x * y;
long ax = Math.abs(x);
long ay = Math.abs(y);
if (((ax | ay) >>> 31 != 0)) {
// Some bits greater than 2^31 that might cause overflow
// Check the result using the divide operator
// and check for the special case of Long.MIN_VALUE * -1
if (((y != 0) && (r / y != x)) ||
(x == Long.MIN_VALUE && y == -1)) {
throw new ArithmeticException("long overflow");
}
}
return r;
}
如何使用?
直接調用是最方便的,但是為了追求速度,應該修改一下,理解判斷思路,因為異常是十分耗時的操作,無腦異常有可能超時
寫這個的目的
總結一下,也方便告訴他人Java幫我們寫好了函數。
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java 加法 溢出_StackOverflow热帖:Java整数相加溢出怎么办?Java8一步搞定~的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: msi台式曲面电脑显示器(msi曲面屏)
- 下一篇: centos 远程安装java程序_ce