Swap without temp using arithmetic

Swap without temp using arithmetic

Medium Java Variables 23 views
Explanation Complexity

Problem Statement

Task: swap two ints without temp using + and - and return [b,a].

Input Format

Two integers a and b

Output Format

An array [b, a] (values swapped)

Example

5 3
[3, 5]

Constraints

• Avoid overflow

• Do not use temporary variable

Concept Explanation

We use arithmetic operations to swap values.

Formula:

1.a = a + b

2.b = a - b

3.a = a - b

After these steps, values are exchanged.

Step-by-Step Explanation

1.Read integers a and b.

2.Set a = a + b.

3.Set b = a - b.

4.Set a = a - b.

5.Return [a, b] (which is [b, a] original).

Concept Explanation

We use arithmetic operations to swap values.

Formula:

1.a = a + b

2.b = a - b

3.a = a - b

After these steps, values are exchanged.

Step-by-Step Explanation

1.Read integers a and b.

2.Set a = a + b.

3.Set b = a - b.

4.Set a = a - b.

5.Return [a, b] (which is [b, a] original).

Input / Output Format

Input Format
Two integers a and b
Output Format
An array [b, a] (values swapped)
Constraints
• Avoid overflow

• Do not use temporary variable

Examples

Input:
5 3
Output:
[3, 5]

Example Solution (Public)

Java
static int[] swapNoTemp(int a,int b){a=a+b;b=a-b;a=a-b;return new int[]{a,b};}

Official Solution Code

static int[] swapNoTemp(int a,int b){a=a+b;b=a-b;a=a-b;return new int[]{a,b};}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.