交换黑白拖曳变量而没有第三个变量 [英] Swaping b/w Tow varaibles with out third variable

查看:73
本文介绍了交换黑白拖曳变量而没有第三个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我..

hi can any one tell me ..
is it possible value swap b/w two variables with out third variable...?

推荐答案

int a = 20,b = 30;

//在交换值之前为a = 20和b = 30


a = a + b; //现在a = 50和b = 30
b = a-b; //现在a = 50和b = 20
a = a-b; //现在a = 30和b = 20


//在交换值是a = 30和b = 20之后
int a=20, b=30;

// before swapping values are a= 20 and b=30


a = a+b ; // now a = 50 and b= 30
b = a-b; // now a = 50 and b = 20
a = a-b; // now a = 30 and b= 20


// after swapping values are a= 30 and b = 20


不,您不能这样做.您为什么介意使用第三个变量?

[更新]
看起来(例如,看到交换2个变量的内容 [
No, you cannot do that. Why do you mind using the third variable?

[update]
It looks (see, for instance, Swapping content of 2 vars[^]) you actually can, but is less efficient (and it has, in my opinion some caveats).
[/update]


我倾向于拒绝:

您需要在某个地方存储其中一个值,即您必须先从目标指针获取值并将其存储在其他位置,然后才能将b写入w或w写入b.
否则,一旦您将w写入b或反之亦然,您将丢失想要交换的数据的一半.
I would be inclined to say no:

You need somewhere to store one of the values i.e. You can''t write b to w or w to b without first taking the value from the target pointer and storing it else where.

Otherwise, as soon you write w to b or visa versa you will have lost half the data you''re looking to swap.


这篇关于交换黑白拖曳变量而没有第三个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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