-->

Swapping two numbers using only two variables

2019-07-06 21:29发布

问题:

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???

回答1:

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)


回答2:

The correct algorithm should be:

a = a + b 
b = a - b
a = a - b 


回答3:

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;


回答4:

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