-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOverflowCheck.java
More file actions
37 lines (33 loc) · 1.13 KB
/
Copy pathOverflowCheck.java
File metadata and controls
37 lines (33 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class OverflowCheck {
public static int safeAdd(int x, int y) {
if (y>0 ? x > Integer.MAX_VALUE - y
: x < Integer.MIN_VALUE - y) {
throw new ArithmeticException("Integer overflow");
}
return x + y;
}
public static int safeSubtract(int x, int y) {
if (y>0 ? x < Integer.MIN_VALUE + y
: x > Integer.MAX_VALUE + y) {
throw new ArithmeticException("Integer overflow");
}
return x - y;
}
/*
* Be careful here!!!
*/
public static int safeMultiply(int x, int y) {
if (y>0 ? (x > Integer.MAX_VALUE/y || x < Integer.MIN_VALUE/y)
: (y < -1 ? (x < Integer.MAX_VALUE/y || x > Integer.MIN_VALUE/y)
: (y == -1 && x == Integer.MIN_VALUE))) {
throw new ArithmeticException("Integer overflow");
}
return x * y;
}
public static int safeDivide(int x, int y) {
if (x == Integer.MIN_VALUE && y == -1) {
throw new ArithmeticException("Integer overflow");
}
return x/y;
}
}