交换两个变量值得方法总结了一下
使用中间变量
int n1=11, n2=10; int tmp = n1; n1 = n2; n2 = tmp; Printf("n1=%d,n2=%d", n1, n2); return 0;
加减法
int n1 = 11, n2 = 10; n1 = n1 + n2; n2=n1-n2; n1 = n1 - n2; Printf("n1=%d,n2=%d", n1, n2); return 0;
堆栈
int n1 = 11, n2 = 10; n2 = n1 + (n1 = n2) * 0; Printf("n1=%d,n2=%d", n1, n2); return 0;
一个值经过同一个数的两次异或后值不变
int n1 = 11, n2 = 10; n1 = n1 ^ n2; n2 = n2 ^ n1; n1 = n1 ^ n2; printf("n1=%d,n2=%d", n1, n2); return 0;
时间: 2024-10-24 09:55:57