MeetCode
Swap without temp using arithmetic
C
C++
Computer Mathematics
CSS
DSA
HTML
Java
JavaScript
NodeJS
PHP
Programming Interview
Python
ReactJS
SQL
Run
Submit
Dark
Problem Statement
Solutions
Submissions
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
Input
5 3
Output
[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
Wrap
Copy
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
C
C++
Computer Mathematics
CSS
DSA
HTML
Java
JavaScript
NodeJS
PHP
Programming Interview
Python
ReactJS
SQL
Test Cases
Output
Submission Result
Input
5 3
Expected Output
[3, 5]
Compile Output
Error
Output
Please
login
to submit solutions.