Skip to content

Instantly share code, notes, and snippets.

@georgimanov
Created April 21, 2017 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgimanov/f2aac15d21d2b131983c5214d5b2c39f to your computer and use it in GitHub Desktop.
Save georgimanov/f2aac15d21d2b131983c5214d5b2c39f to your computer and use it in GitHub Desktop.
Swap Too Numbers
using System;
namespace SwapTooNumbers
{
public class StartUp
{
// How to swap to numeric values
public static void Main(string[] args)
{
int first = 1;
int second = 2;
// with temp variable
Console.WriteLine("Swap with temporary variable: ");
SwapWithTempVariable(first, second);
// without temp variable - XOR(^)
Console.WriteLine("Swap without temp variable using XOR(^): ");
SwapWithXOR(first, second);
// with only plus and minus
Console.WriteLine("Swap without temp variable using plus(+) and minus(-): ");
SwapWithPlusAndMinus(first, second);
}
private static void SwapWithPlusAndMinus(int first, int second)
{
first = first + second;
second = first - second;
first = first - second;
PrintResult(first, second);
}
private static void SwapWithXOR(int first, int second)
{
first = first ^ second;
second = second ^ first;
first = first ^ second;
PrintResult(first, second);
}
private static void SwapWithTempVariable(int first, int second)
{
var temp = first;
first = second;
second = temp;
PrintResult(first, second);
}
private static void PrintResult(int first, int second)
{
Console.WriteLine(first);
Console.WriteLine(second);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment