Java中 int 的溢出问题
int 是一种整型变量,是一种常用的数据类型,存放的是整数值,其取值范围是占用 4 字节 32 bit时的取值范围是 -2^31到 2^31-1 也就是 - 2147483648~2147483647,当我们的计算值超出这个范围时就会产生溢出问题。
溢出解决方法
为了避免 int 类型的溢出,可以在该表达式中的任一常量后加上大写的“L”,或
是在变量前面加上 long,作为强制类型的转换。
//递归计算强转int 溢出的最后值
public static int a(long d) {
long e = 0;
if (d > 2147483647) {
e = -(d - 2147483647);
a(e);
} else if (d < -2147483648) {
e = -(d + 2147483647 + 1);
a(e);
}
return (int) e;
}
在整型中,能够保存的数值范围最大的是long型;在浮点型中,能够保存的数值范围最大的是double型。所以在遇到数据溢出问题时,我们可以先把能够保存的数值范围少的类型转换为多的类型,再进行运算。
public static void main(String args []){
int a = 2147483647;//定义一个int型变量a的值为int型能够保存的最大值
long b = (long)a;//因为我们要在最大值的基础上继续增加数字,所以要先进行数据转换
System.out.println(b+2);
}
溢出的三种类型以及判断
相加溢出
public class Main {
public static void main(String[] args) {
int x = Integer.MAX_VALUE,y = Integer.MAX_VALUE;
int z = x+y;
System.out.println("x与y相加溢出的结果:"+z);
if(((x^z)&(y^z))<0) {
System.out.println("相加溢出");
}
}
}
输出:
x与y相加溢出的结果:-2
相加溢出
相减溢出
public class Main {
public static void main(String[] args) {
int x = Integer.MAX_VALUE,y = Integer.MIN_VALUE;
int z = x-y;
System.out.println("x与y相加溢出的结果:"+z);
if(((x^z)&(y^z))<0) {
System.out.println("相加溢出");
}
}
}
相乘溢出
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;
}