不使用临时存储就交换两个值. [英] SWAP two value without using temp storage..

查看:63
本文介绍了不使用临时存储就交换两个值.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有问题,

int X = 150;
整数y = 45;

我必须在不使用临时变量的情况下交换两个值.

结果应该是这样的:

X = 45

y = 150

任何解决方案的人.,谢谢

hi guys, i have a problem here,

int X = 150;
int y = 45;

i must swap the two values without using a temporary variable.

result should be like this:

X = 45
and
y=150

any solutions guys., thanks

推荐答案

经典方法是使用XOR 3次:

The classic way is to use XOR three times:

a ^= b;
b ^= a;
a ^= b;


现在去弄清楚它为什么起作用!


Now go figure out why it works!


在这里,你去!
Here you go!
int x = 10
int y = 20

x = x+y;
y = x-y;
x = x-y;

// Print swapped values!
cout << x    //20
cout << y    //10


我认为复杂的解决方案,其中包括计算每个位是否不同,如果存在,则将它们交换.但是,这似乎是一件迟钝的事情.
I can think of a convoluted solution, which involves working out if each bit is different, and if it is, swapping them both. It seems like a retarded thing to do, however.


这篇关于不使用临时存储就交换两个值.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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