如何在不使用任何 if 条件、强制转换或附加变量的情况下交换两个整数变量? [英] How do you swap two integer variables without using any if conditions, casting, or additional variables?

查看:25
本文介绍了如何在不使用任何 if 条件、强制转换或附加变量的情况下交换两个整数变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个整数变量.您能否在不使用任何 if 条件、不强制转换和不使用其他变量的情况下交换这些整数变量?例如:

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 总是.答案应该是 a == 5b == 10

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

推荐答案

如果您认为不使用第三个变量是聪明,那么进行一些性能测试,您会发现更快的方法是使用第三个 int 临时存储变量.

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;

这篇关于如何在不使用任何 if 条件、强制转换或附加变量的情况下交换两个整数变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆