forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIntegerOverflow.java
58 lines (52 loc) · 1.44 KB
/
IntegerOverflow.java
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.rampatra.bits;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 6/4/15
* @time: 4:28 PM
*/
public class IntegerOverflow {
/**
* Adds {@param a} and {@param b} and if the result can't
* be stored as an integer it throws an exception
*
* @param a
* @param b
* @return
*/
public static int add(int a, int b) throws Exception {
if (a > Integer.MAX_VALUE - b) {
throw new Exception("Integer Overflow");
} else {
return a + b;
}
}
/**
* Adds {@param a} and {@param b} and if the result can't
* be stored as an integer it throws an exception
*
* @param a
* @param b
* @return
*/
public static int add_V1(int a, int b) throws Exception {
if ((a > 0 && b > 0 && a + b < 0) || (a < 0 && b < 0 && a + b > 0)) {
throw new Exception("Integer Overflow");
} else {
return a + b;
}
}
public static void main(String[] args) {
try {
System.out.println(add(2, 3));
System.out.println(add(2147483647, 999999999));
System.out.println(add(-2147483647, -999999999));
System.out.println(add_V1(2, 3));
System.out.println(add_V1(2147483647, 999999999));
System.out.println(add_V1(-2147483647, -999999999));
} catch (Exception e) {
e.printStackTrace();
}
}
}