Swap Two Numbers
Problem
Read two integers. Swap their values and print them in the form After swap: first=<a> second=<b>. Example: the input 3 7 gives After swap: first=7 second=3.
Constraints
- -10^9 <= each number <= 10^9
Examples
Input
3 7
Output
After swap: first=7 second=3
Solutions
A glass of water can not be poured into a glass that is full. We need a third glass. In the same way we need a temporary variable to keep one value safe.
/*
* Problem : Swap two numbers.
* Input : Two integers.
* Output : The two numbers after the swap.
* Approach: Use a temporary variable.
* 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 first = scanner.nextInt();
int second = scanner.nextInt();
// Step 1: Save the first value in a temporary variable. Without it, we would lose the value.
int temporary = first;
// Step 2: Copy the second value into the first variable.
first = second;
// Step 3: Copy the saved value into the second variable.
second = temporary;
// Step 4: Print the result.
System.out.println("After swap: first=" + first + " second=" + second);
}
}
Hints (1)
- What happens if you copy second into first without saving first?