Reputation: 185
How is it performing swapping?
a=a+b
b=a+b
a=b+a
I don't agree that it's swap to a book!!!
The book options include "complements of values of a and b", "negate and b". Hope these options aren't satisfying it too???
Upvotes: 3
Views: 5947
Reputation: 173552
The swap is performed using XOR, which is typically written as a plus within a circle (⊕); for example:
a := 5
b := 7
a := a xor b (2)
b := a xor b (5)
a := b xor a (7)
Upvotes: 9
Reputation: 372
We can use XOR (^) for this. Advantage of XOR : As XOR works on bit level, it takes very less amount of time than any other operations. If a = 5 and b = 7 then to swap :
a = a ^ b
b = a ^ b
a = a ^ b
Where '^' means XOR. Result : a = 7 and b = 5
Upvotes: 0
Reputation:
I recently underwent an interview for java fresher, the interviewer asked me to perform swapping of two numbers (but in one line).
Swapping of two numbers can be performed in one line also, without using a temp variable.
The logic is really simple,
x is added with y in the same line, y is assigned as x which is subtracted by their sum.
after performing this one line arithmetics the numbers were swapped. (only in one line)
public class SwapInOneLine {
public static void main(String[] args) {
int x = 10; int y = 20;
System.out.println("Before Swaping: x = " + x + " and y= " + y);
x = x + y - (y = x);
System.out.println("After Swaping: x = " + x + " and y= " + y);
}}
output:
Before Swaping: x = 10 and y= 20
After Swaping: x = 20 and y= 10
Upvotes: 0
Reputation: 4453
Actually, it can be done by two ways:
int a = 5, b = 10;
Using Addition(+) and Subtraction(-)
a = a + b;
b = a - b;
a = a - b;
Using Multiple(*) and Division(/)
a = a * b;
b = a / b;
a = a / b;
Upvotes: -1