How to swap two numbers without using a temp variable, write code which is free from Integer overflow?
Here we will discuss how to swap two numbers without using a temp variable in C#
Swap two numeric values(like int, float etc) without a temporary variable as follows:
ANS:
a = a + b ;
b = a – b ;
a = a – b ;
We can also use XOR(^) operator for the same :
a = a^b;
b = b^a;
a = a^b;
This is a frequently asked interview question. Let’s look at the implementation in C#.
Without Using temp variable:
class Program
{
static void Main(string[] args)
{
int first, second;
first = 100;
second = 200;
first = first + second;
second = first - second;
first = first - second;
Console.WriteLine(first.ToString());
Console.WriteLine(second.ToString());
Console.ReadLine();
}
}
Output:
200
100
Program to swap numbers using XOR Operator:
ANS:
using System;
class Program
{
static void Main()
{
int first, second;
first = 100;
second = 200;
//swap numbers using XOR
first = second^first;
second = second^first;
first = first^second;
Console.WriteLine("first = " + first);
Console.WriteLine("second = " + second);
}
}
Output:
200
100.
Here we will discuss how to swap two numbers without using a temp variable in C#
Swap two numeric values(like int, float etc) without a temporary variable as follows:
ANS:
a = a + b ;
b = a – b ;
a = a – b ;
We can also use XOR(^) operator for the same :
a = a^b;
b = b^a;
a = a^b;
This is a frequently asked interview question. Let’s look at the implementation in C#.
Without Using temp variable:
class Program
{
static void Main(string[] args)
{
int first, second;
first = 100;
second = 200;
first = first + second;
second = first - second;
first = first - second;
Console.WriteLine(first.ToString());
Console.WriteLine(second.ToString());
Console.ReadLine();
}
}
Output:
200
100
Program to swap numbers using XOR Operator:
ANS:
using System;
class Program
{
static void Main()
{
int first, second;
first = 100;
second = 200;
//swap numbers using XOR
first = second^first;
second = second^first;
first = first^second;
Console.WriteLine("first = " + first);
Console.WriteLine("second = " + second);
}
}
Output:
200
100.
Post a Comment