-3

I am new to coding and practicing leetcode problems. Integer reverse problem talks about overflow.

I have searched and most of the discussion about how to handle the overflow. Could someone explain what is this overflow and why is this caused?

Karthik
  • 107
  • 1
  • 10
  • I would read this Q/A: https://stackoverflow.com/questions/3001836/how-does-java-handle-integer-underflows-and-overflows-and-how-would-you-check-fo – GBlodgett Oct 24 '18 at 23:40
  • 1
    thank you for directing me to that thread. it helps – Karthik Oct 24 '18 at 23:43

1 Answers1

1

Integer.MAX_VALUE is 2147483647.
If you reverse that, you get 7463847412.

That value is obviously outside the range supported by int.
If you calculate the reverse, you'll get silent overflow.

int rev = 0;
for (int val = Integer.MAX_VALUE; val != 0; val /= 10)
    rev = rev * 10 + val % 10;
System.out.println(rev); // prints: -1126087180   <== Result of overflow

If you parse reversed string, you'll get parse exception.

String revStr = new StringBuilder().append(Integer.MAX_VALUE).reverse().toString();
System.out.println(revStr); // prints: 7463847412
rev = Integer.parseInt(revStr); // throws: NumberFormatException: For input string: "7463847412"

You can also guard against overflow by using the xxxExact methods of Math:

int rev = 0;
for (int val = Integer.MAX_VALUE; val != 0; val /= 10)
    rev = Math.addExact(Math.multiplyExact(rev, 10), val % 10); // throws: ArithmeticException: integer overflow
Andreas
  • 154,647
  • 11
  • 152
  • 247