Swap Two Numbers

beginner Programming Basics

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

Best approachTime O(1)Space O(1)

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.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * 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)
  1. What happens if you copy second into first without saving first?