How do you swap two integer variables without using any if conditions, casting, or additional variables? [closed]

蹲街弑〆低调 提交于 2019-11-27 15:40:14

If you think you are being clever by not using 3rd variable then do some performance tests and you see that the much faster way is to use 3rd int to store the variable temporarily.

Anyways, i solved the problem with XOR bitwise operator:

a ^= b;
b ^= a;
a ^= b;
a=a+b;
b=a-b;
a=a-b;

It's a little trick.

int a = 5;
int b= 10;
a = a+b;
b = a-b; /* Really (a+b) - b i.e. a */
a = a-b; /* Really (a+b) - a i.e. b */

simple try this

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

and that's it

yes you can do it By using plus/minus operation.

Example:
num1 = num1 + num2;                
num2 = num1 - num2;                
num1 = num1 - num2;
Mayur
a=a+b
b=a-b
a=a-b

That's it!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!