参加腾讯的后台面试,问我 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;
}