Java中a+b溢出了怎么办?

参加腾讯的后台面试,问我 a,b交换值,不用第三个变量怎么办
回答如下:
1.
异或
a= a^b
b = a^b;
a = a^b;
2.
a = a+b;
b = a -b;
a = a-b;

问题来了?
问 a+b会不会溢出呢,答:会
问 溢出了怎么办呢 答:不知道! 然后:挂!

加法溢出

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
相加溢出

相减溢出

        x = Integer.MAX_VALUE;
		y = Integer.MIN_VALUE;
		z = x-y;
		System.out.println("x与y相减的结果"+(x-y));
		if(((x^y)&(x^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;
    }

注意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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值