开发者

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

开发者 https://www.devze.com 2023-01-08 02:07 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

There are two integer variables. Can you swap those integer variables without using any if conditions, without casting, and without using additional variables? For example:

int a = 10;
int b = 5;

a > b always. The answer should be a == 5 开发者_JAVA技巧and b == 10


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;


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

That's it!

0

精彩评论

暂无评论...
验证码 换一张
取 消