MFlower——朝花夕拾

                                   有你有我
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

交换两个整数的值的几种方法

Posted on 2008-11-26 23:28  MFlower  阅读(271)  评论(0)    收藏  举报

方法1:

using System;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    
public static void Main()
    {
        
int a = -5;
        
int b = 3;
        Swap(
ref a, ref b);
        Console.WriteLine(
"a={0},b={1}",a,b);
    }

    
public static void Swap(ref int a, ref int b)
    {
        
int temp = a;
        a 
= b;
        b 
= temp;
    }
}

 

方法2:

using System;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    
public static void Main()
    {
        
int a = -5;
        
int b = 3;
        Swap(
ref a, ref b);
        Console.WriteLine(
"a={0},b={1}",a,b);
    }

    
public static void Swap(ref int a, ref int b)
    {
        a 
= a ^ b;
        b 
= a ^ b;
        a 
= a ^ b;
    }
}

 

方法3:

using System;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    
public static void Main()
    {
        
int a = -5;
        
int b = 3;
        Swap(
ref a, ref b);
        Console.WriteLine(
"a={0},b={1}",a,b);
    }

    
public static void Swap(ref int a, ref int b)
    {
        a 
= a + b;
        b 
= a - b;
        a 
= a - b;
    }
}