32-bit Integer Overflow
Problem
Read two integers a and b. Each one fits in a signed 32-bit integer (-2147483648 to 2147483647). Print a + b as a signed 32-bit integer would store it. If the real sum is too big or too small, the value wraps around. Example: 2147483647 + 1 gives -2147483648.
Constraints
- -2^31 <= a, b <= 2^31 - 1
Examples
Input
2147483647 1
Output
-2147483648
Solutions
A 32-bit int has only 2^32 different values. After the largest value the counter goes to the smallest value, like a car odometer. Java does this silently. JavaScript and Python need an explicit step to show the same behaviour.
Math.addExact (Java 8) throws an exception on overflow instead of wrapping.
/*
* Problem : Add two 32-bit integers like a computer does.
* Input : Two integers in the 32-bit signed range.
* Output : Their sum as a 32-bit signed integer.
* Approach: The sum wraps around when it is too big.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
// Step 1: Add two int values. Java does this in 32 bits and wraps around without an error.
int sum = a + b;
// Step 2: Print the result.
System.out.println(sum);
}
}
Hints (2)
- How many different values does a 32-bit integer have?
- What is the result of the largest int plus 1?