Swap Number Without Temporary Variable
Given two variables ‘X’ and ‘Y’. Your task is to swap the number without using a temporary variable or third variable.
Swap means the value of ‘X’ and ‘Y’ must be interchanged. Take an example ‘X’ is 10 and ‘Y’ is 20 so your function must return ‘X’ as a 20 and ‘Y’ as a 10.
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.
Next ‘T’ lines contain two space-separated integers ‘X’ and ‘Y’ which represent the next ‘T’ test cases.
Output Format
For each test case, return an array/vector that contains two integers ‘X’ and ‘Y’ with a swapped value.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 2*10^5
-10^9 <= X,Y <= 10^9
Where ‘T’ is the total number of test cases, ‘X’ and ‘Y’ denotes two given integer variables.
Time limit: 1 second
CodingNinjas
author
2y
Addition Approach
- Idea is to get the sum of given two-variable ‘X’ and ‘Y’ in an ‘X’ = ‘X’ + ‘Y’.
- Value of swapped ‘Y’ can get by ‘X’ - ‘Y’ = (‘X’ + ‘Y’) - ‘Y’ = ‘X’
- Value of swapped ‘X’ can get by ‘X’ -...read more
CodingNinjas
author
2y
Multiplication Approach
- Idea is to get the multiplication of given two-variable ‘X’ and ‘Y’ in an ‘X’ = ‘X’ * ‘Y’.
- Value of swapped ‘Y’ can get by ‘X’ / ‘Y’ = ‘X’
- Value of swapped ‘X’ can get by ‘X’ / ‘Y...read more
CodingNinjas
author
2y
Bitwise XOR Approach
- We use Bitwise XOR property
- t^0=t
- t^t=0
- With help of these properties, we swap the number ‘X' and ‘Y’
- ‘X' = ‘X' ^ ‘Y’
- ‘Y’ = ‘X' ^ ‘Y’ this is the same as ‘Y’ = (‘X' ^ ‘Y’ ) ^ ‘Y’ = ‘X' ...read more
CodingNinjas
author
2y
Bitwise sum
- We get the value of sum by this formula ‘X' = ('X'&'Y') + ('X' | ‘Y’) and subtraction by this formula ‘Y' = ‘X' + (~‘Y') +1’ it is same as ‘Y' = ‘X' - ‘Y'.
- apply solution 1
- For sum , ‘X' = (‘...read more
Add answer anonymously...
Top Nvidia Software Developer Intern interview questions & answers
Popular interview questions of Software Developer Intern
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app