File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ package me .ramswaroop .bits ;
2
+
3
+ /**
4
+ * Created by IntelliJ IDEA.
5
+ *
6
+ * @author: ramswaroop
7
+ * @date: 6/4/15
8
+ * @time: 4:28 PM
9
+ */
10
+ public class IntegerOverflow {
11
+
12
+ /**
13
+ * Adds {@param a} and {@param b} and if the result can't
14
+ * be stored as an integer it throws an exception
15
+ *
16
+ * @param a
17
+ * @param b
18
+ * @return
19
+ */
20
+ public static int add (int a , int b ) throws Exception {
21
+
22
+ if (a > Integer .MAX_VALUE - b ) {
23
+ throw new Exception ("Integer Overflow" );
24
+ } else {
25
+ return a + b ;
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Adds {@param a} and {@param b} and if the result can't
31
+ * be stored as an integer it throws an exception
32
+ *
33
+ * @param a
34
+ * @param b
35
+ * @return
36
+ */
37
+ public static int add_V1 (int a , int b ) throws Exception {
38
+
39
+ if ((a > 0 && b > 0 && a + b < 0 ) || (a < 0 && b < 0 && a + b > 0 )) {
40
+ throw new Exception ("Integer Overflow" );
41
+ } else {
42
+ return a + b ;
43
+ }
44
+ }
45
+
46
+ public static void main (String a []) {
47
+ try {
48
+ System .out .println (add (2 , 3 ));
49
+ System .out .println (add (2147483647 , 999999999 ));
50
+ System .out .println (add (-2147483647 , -999999999 ));
51
+ System .out .println (add_V1 (2 , 3 ));
52
+ System .out .println (add_V1 (2147483647 , 999999999 ));
53
+ System .out .println (add_V1 (-2147483647 , -999999999 ));
54
+ } catch (Exception e ) {
55
+ e .printStackTrace ();
56
+ }
57
+ }
58
+ }
You can’t perform that action at this time.
0 commit comments