AtCoder Beginner Contest 161 The number of contestants is 9927 fast, see all questions 5 minutes after the start of the contest
AtCoder Beginner Contest 161 A ABC Swap variable exchange / addition / subtraction exchange / exclusive OR exchange
See https://blog.csdn.net/mrcrack/article/details/104454762 for the general catalog
Online evaluation address https://atcoder.jp/contests/abc161/tasks/abc161_a
Method 1: Variable exchange
Use intermediate variables for exchange.
#include <stdio.h>
int main(){
int x,y,z,t;
scanf("%d%d%d",&x,&y,&z);
t=x,x=y,y=t;
t=x,x=z,z=t;
printf("%d %d %d\n",x,y,z);
}
Method 2: Addition and subtraction
Exchange using addition and subtraction
The derivation is as follows:
x + yy = x , x + yx = y
Note that when the value is relatively large, the result of the addition calculation may overflow.
#include <stdio.h>
int main(){
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
x=x+y,y=x-y,x=x-y;
x=x+z,z=x-z,x=x-z;
printf("%d %d %d\n",x,y,z);
}
Method 3: XOR exchange
The derivation is as follows:
x ^ y ^ y = x ^ (y ^ y) = x ^ 0 = x, x ^ y ^ x = x ^ x ^ y = (x ^ x) ^ y = 0 ^ y = y
Exchange using XOR operation
#include <stdio.h>
int main(){
int x,y,z,t;
scanf("%d%d%d",&x,&y,&z);
x=x^y,y=x^y,x=x^y;
x=x^z,z=x^z,x=x^z;
printf("%d %d %d\n",x,y,z);
}