且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何交换两个号码,而无需使用第三个变量?

更新时间:2023-01-31 11:15:13

 无效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
}