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?
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?
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