交换两个变量常规四种做法
#include <stdio.h> void swap1(int a,int b) { a = a ^ b; b = a ^ b; a = a ^ b; //a^b^a printf("%d,%d\n",a,b); } void swap2(int a,int b) { a = a + b; b = a - b; a = a - b; printf("%d,%d\n",a,b); } void swap3(int a,int b) { int t = a; a = b; b = t; printf("%d,%d\n",a,b); } void swap4(int a,int b) { a = a * b; b = a / b; a = a / b; printf("%d,%d\n",a,b); } int main () { int a = 3; int b = 4; swap1(a,b); swap2(a,b); swap3(a,b); swap4(a,b); return 0; }
这四类在面试过程中常被问到,希望大家掌握一下。