不使用第三个变量交换两个数字

本文介绍了三种交换两个整数的技巧:借助第三方变量、利用求和和位运算之异或。并解释了每种方法的优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

交换两个数字:

 1 using System;
 2 
 3 namespace ConsoleApplication
 4 {
 5     class Program
 6     {
 7         static void Main(string[] args)
 8         {
 9             // 交换2个数字的方法
10 
11             int a = 3, b = 5;
12             int c = 0;
13 
14             // 方法1:借助第三方临时变量
15             // 有点:阅读性强,开发时使用.
16             Console.WriteLine("before switch: a={0},b={1},c={2}", a, b, c);
17 
18             c = a;
19             a = b;
20             b = c;
21 
22             Console.WriteLine("after switch: a={0},b={1},c={2}", a, b, c);
23 
24             // 方法2: 求和:根据总和得之各个变量的值
25             // 去点:如果两个数值过大,会超出int范围,溢出。
26             // 不需要第三方变量交换2个数字
27             Console.WriteLine("before switch: a={0},b={1}", a, b);
28             a = a + b;
29             b = a - b;
30             a = a - b;
31             Console.WriteLine("after switch: a={0},b={1}", a, b);
32 
33 
34             // 方法3:位运算之异或
35             // 规律:一个数异或同一个数2次,结果还是这个数.
36             // 缺点:阅读性差
37             Console.WriteLine("before switch: a={0},b={1}", a, b);
38             a = a ^ b;
39             b = a ^ b;
40             a = a ^ b;
41             Console.WriteLine("after switch: a={0},b={1}", a, b);
42 
43             Console.WriteLine(2 << 3);
44 
45             Console.ReadKey();
46         }
47     }
48 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值