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

2023-09-11 07:28:59 作者:隐于市

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

解决方案

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

解决方案 C语言中交换两个变量的地址后,两个变量的值是否交换

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
}