如何交换两个号码,而无需使用第三个变量? [英] How to swap two numbers without using third variable?

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

问题描述

我可以使用第三个变量,但解决不了,而无需使用第三个变量解决。

解决方案

 无效swap_int(无符号整数*一,无符号整型* B){
   *一个^ = * B; //那之后:一个==(orig_a ^ orig_b)
   * B ^ = * A; //那之后:乙==(orig_b ^一)==(orig_b ^ orig_a ^ orig_b)== orig_a,因而被转移到b
   *一个^ = * B; //后认为:一==(orig_a ^ orig_b)^ B ==(orig_a ^ orig_b)^ orig_a == orig_b,因此我们很高兴,并准备
}
 

I can solve it using third variable but can't solve without using third variable.

解决方案

void swap_int(unsigned int *a, unsigned int *b) {
   *a^=*b; // After that: a==(orig_a ^ orig_b)
   *b^=*a; // After that: b==(orig_b ^ a)==(orig_b ^ orig_a ^ orig_b)==orig_a, thus a was moved to b
   *a^=*b; // After that: a==(orig_a ^ orig_b) ^ b==(orig_a ^ orig_b) ^ orig_a==orig_b, thus we are happy and ready
}

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

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