如何交换,而无需使用临时变量或算术运算的两个数字? [英] How to swap two numbers without using temp variables or arithmetic operations?

查看:152
本文介绍了如何交换,而无需使用临时变量或算术运算的两个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此公式交换两个数字没有一个临时变量,但使用算术运算:

This equation swaps two numbers without a temporary variable, but uses arithmetic operations:

a = (a+b) - (b=a);

我怎么能做到这一点,而不算术运算?我在想XOR。

How can I do it without arithmetic operations? I was thinking about XOR.

推荐答案

XOR算法交换

注意:不要使用这个,除非你绝对要(即你正在写超优化的汇编程序)。文章给出了一些原因没有。

Note: Don't use this unless you absolutely have to (i.e. you are writing hyper-optimised assembler). The article gives some reasons why not.

这篇关于如何交换,而无需使用临时变量或算术运算的两个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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