How do you exchange two integer variables without any conditions, castings or additional variables?

There are two integer variables. Can you exchange these integer variables without any conditions, without casting and without using additional variables? For instance:

int a = 10; int b = 5; 

a > b always. The answer should be a == 5 and b == 10

+5
source share
6 answers

If you think you are using smart without using a third variable, do some performance testing and you will see that a much faster way is to use the 3rd int to store the variable temporarily.

In any case, I solved the problem with the bitwise XOR operator:

 a ^= b; b ^= a; a ^= b; 
+13
source
 a=a+b; b=ab; a=ab; 
+10
source

This is a little trick.

 int a = 5; int b= 10; a = a+b; b = ab; /* Really (a+b) - b ie a */ a = ab; /* Really (a+b) - a ie b */ 
+4
source

Yes, you can do this using the plus / minus operation.

 Example: num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2; 
+3
source
 a=a+b b=ab a=ab 

What is it!

+3
source

try it

 a=a+b; b=ab; a=ab; 

and what is he

+3
source

Source: https://habr.com/ru/post/952148/


All Articles