Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何不采用第3个变量进行两个变量值的交换 #1

Open
wenuanhappy opened this issue Sep 19, 2016 · 9 comments
Open

如何不采用第3个变量进行两个变量值的交换 #1

wenuanhappy opened this issue Sep 19, 2016 · 9 comments

Comments

@wenuanhappy
Copy link

大家可以上代码

@geeeeeeeeek geeeeeeeeek changed the title 课后思考题 【如何不采用第3个变量进行两个变量值的交换】, 如何不采用第3个变量进行两个变量值的交换 Sep 19, 2016
@air1234
Copy link

air1234 commented Sep 20, 2016

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

1 similar comment
@wz-WillZheng
Copy link

wz-WillZheng commented Sep 20, 2016

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

@Mashiroangel
Copy link

Mashiroangel commented Sep 20, 2016

x = x * y;
y = x / y;
x = x / y;

@mondaylord
Copy link

mondaylord commented Sep 20, 2016

x = 10 * x + y;
y = x / 10;
x = x % 10;

@lixiangmin
Copy link

lixiangmin commented Sep 20, 2016

X=X+Y
Y=X-2*Y
X=(X-Y)/2
Y=Y+X

@junyuanjun
Copy link
Member

@longjingqi 你看 x = x % 10 这句话,最后的结果x总是一个一位数啊。你可以带入 x = 23, y = 25就会发现有问题。

@junyuanjun
Copy link
Member

@Mashiroangel 你的方法可以实现非0的交换,但是如果x和y中有一个是0就比较不好办了

@junyuanjun
Copy link
Member

junyuanjun commented Sep 21, 2016

我看大家仿佛没有回复了,说一个比较有趣的不用第三个变量的数值交换的方法吧 :P

x = x ^ y;
y = x ^ y;
x = x ^ y;

这里^是xor操作,中文翻译是异或,这是一种二进制操作(把操作数化成二进制以后进行相关处理);有兴趣的同学可以看看二进制的相关资料,xor也有很多很有趣的性质。

@zhty
Copy link

zhty commented Sep 21, 2016

x=(x+y)/2
y=y-x
x=x+y
y=x-2y

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

9 participants