Array ( [0] => [1] => questions [2] => Basic [3] => Swapping-of-Two-Numberss )
Given two integers. You have to swap those two numbers and print it.
First line contains two integers separated by space.
Print the numbers after swapping.
1 3
3 1
5 7
7 5
10 12
12 10
Login to see Discussion
Approach 1: using temporary variable
i) store first number in temp variable
ii)store second in first number
iii)assign temp to second number
Time Complexity: O(1)
Space Complexity: O(1)
Approach 2: using addtion
i) in first number store the sum of two numbers
ii)in second number store the difference of two numbers
iii)in first number store the difference of two numbers
Time Complexity: O(1)
Space Complexity: O(1)
Approach 3: using multiplication and division
Note this approach doesn't work if any of the two numbers is zero
i) in first number store the product of two numbers
ii)in second number store the division of two numbers
iii)in first number store the division of two numbers
Time Complexity: O(1)
Space Complexity: O(1)
Approach 4: using XOR operator
i) in first number store the XOR of two numbers
ii)in second number store the XOR of two numbers
iii)in first number store the XOR of two numbers
Time Complexity: O(1)
Space Complexity: O(1)
Note :
Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.
Login to see Solution