Swapping two variable value without using third va

2019-01-01 10:14发布

One of the very tricky questions asked in an interview.

Swap the values of two variables like a=10 and b=15.

Generally to swap two variables values, we need 3rd variable like:

temp=a;
a=b;
b=temp;

Now the requirement is, swap values of two variables without using 3rd variable.

标签: c++
25条回答
何处买醉
2楼-- · 2019-01-01 11:07

single line solution for swapping two values in c language.

a=(b=(a=a+b,a-b),a-b);
查看更多
几人难应
3楼-- · 2019-01-01 11:08

Consider a=10, b=15:

Using Addition and Subtraction

a = a + b //a=25
b = a - b //b=10
a = a - b //a=15

Using Division and multiplication

a = a * b //a=150
b = a / b //b=10
a = a / b //a=15
查看更多
永恒的永恒
4楼-- · 2019-01-01 11:09
second_value -= first_value;
first_value +=  second_value;
second_value -= first_value;
second_value *= -1;
查看更多
泪湿衣
5楼-- · 2019-01-01 11:10

that's the correct XOR swap algorithm

void xorSwap (int* x, int* y) {
   if (x != y) { //ensure that memory locations are different
      if (*x != *y) { //ensure that values are different
         *x ^= *y;
         *y ^= *x;
         *x ^= *y;
      }
   }
}

you have to ensure that memory locations are different and also that the actual values are different because A XOR A = 0

查看更多
只靠听说
6楼-- · 2019-01-01 11:10
public void swapnumber(int a,int b){
    a = a+b-(b=a);
    System.out.println("a = "+a +" b= "+b);
}
查看更多
余生请多指教
7楼-- · 2019-01-01 11:11
a = a + b - (b=a);

It's very simple, but it may raise a warning.

查看更多
登录 后发表回答