class AddTwoBinaryStrings

{

static void Main(string[] args)

{

ConsoleKeyInfo keyPress;

do

{

Console.WriteLine(“Enter two binary strings:”);

string b1 = Console.ReadLine();

string b2 = Console.ReadLine();

string sum = string.Empty;

int carry = 0, b1Length = b1.Length – 1, b2Length = b2.Length – 1;while (b1Length >= 0 || b2Length >= 0)

{

if (b1Length >= 0)

{

carry += b1[b1Length] – ‘0’;

}

if (b2Length >= 0)

{

carry += b2[b2Length] – ‘0’;

}if (carry == 3)

{

sum = “1” + sum;

carry = 1;

}

else if (carry == 2)

{

sum = “0” + sum;

carry = 1;

}

else

{

sum = carry.ToString() + sum;

carry = 0;

}

–b1Length;

–b2Length;

}

if (carry > 0)

{

sum = “1” + sum;

}Console.WriteLine(sum);

keyPress = Console.ReadKey();

} while (keyPress.Key != ConsoleKey.Escape);

}

}

# Add two binary numbers in C#

Advertisements