首页 > 代码库 > 两个变量交换值的方法

两个变量交换值的方法

  1. 使用中间变量

    

           int n1=10, n2=20;
            int tmp = n1;
            n1 = n2;
            n2 = tmp;
            Console.WriteLine("n1={0},n2={1}", n1, n2);
            Console.ReadKey();

  

     2.加减法

            int n1 = 10, n2 = 20;
            n1 = n1 + n2;
            n2=n1-n2;
            n1 = n1 - n2;
            Console.WriteLine("n1={0},n2={1}", n1, n2);
            Console.ReadKey();

  3.堆栈

            int n1 = 10, n2 = 20;
            n2 = n1 + (n1 = n2) * 0;
            Console.WriteLine("n1={0},n2={1}", n1, n2);
            Console.ReadKey();    

     4.一个值经过同一个数的两次异或后值不变

 

            int n1 = 10, n2 = 20;
            n1 = n1 ^ n2;
            n2 = n2 ^ n1;
            n1 = n1 ^ n2; 
            Console.WriteLine("n1={0},n2={1}", n1, n2);
            Console.ReadKey();