一道簡單面試題:兩個整型不借助中間變量實現值互換的兩種算法
C# Code:
using System;
namespace KiloNet
{
class test2
{
static void Main(string[] args)
{
int a = int.MaxValue;
int b = int.MaxValue-2;
Console.WriteLine("a:{0},b:{1}",a,b);
a = b + (b = a) * 0;
Console.WriteLine("a:{0},b:{1}",a,b);
a = a^b;
b = a^b;
a= b^a;
Console.WriteLine("a:{0},b:{1}",a,b);
Console.Read();
}
}
}
//一道簡單面試題:兩個整型不借助中間變量實現值互換namespace KiloNet
{
class test2
{
static void Main(string[] args)
{
int a = int.MaxValue;
int b = int.MaxValue-2;
Console.WriteLine("a:{0},b:{1}",a,b);
a = b + (b = a) * 0;
Console.WriteLine("a:{0},b:{1}",a,b);
a = a^b;
b = a^b;
a= b^a;
Console.WriteLine("a:{0},b:{1}",a,b);
Console.Read();
}
}
}
//java code 饅頭所有
class test
{
public static void main(String[] args)
{
System.out.println("Hello Kilo!");
int a = 34;
int b = 45;
System.out.println("a="+a + ",b="+ b);
a = a^b;
b = a^b;
a= b^a;
System.out.println("a="+a + ",b="+ b);
a = a+b;
b = a-b;
a= a-b;
System.out.println("a="+a + ",b="+ b);
}
}
//哈哈,這是Java2里看到.