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


    交换两个数字:

     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 }
  • 相关阅读:
    mysql索引失效的N种情况
    JDK,JRE,JVM的区别
    mysql排名函数解析
    mysql经典50道基础练习题(附加答案)
    常用SQL
    Application.DoEvents()
    【转】mapreduce中的全局文件使用方法:以k-means为例
    【转】MapReduce中的Combiner 和 in-Mapper Combining
    Linux 下安装hadoop,伪分布模式配置
    VS2010中配置 CUDA5.5
  • 原文地址:https://www.cnblogs.com/fanyong/p/2829857.html
Copyright © 2020-2023  润新知