ADD 2 BINARY NUMBERS REPRESENTED AS STRINGS
namespace Add2BinNumRepresentedAsStrings
{
class Program
{
public static String Add(String A, String B)
{
String Res = "";
Boolean carry = false;
int i, j;
int a, b, sum;
for (i = A.Length - 1, j = B.Length - 1; i >= 0 || j >= 0; i--, j--)
{
if (i >= 0) a = A[i] - '0';
else a = 0;
if (j >= 0) b = B[j] - '0';
else b = 0;
if (a == 0 || a == 1 && b == 0 || b == 1)
{
sum = a + b;
if (carry) sum++;
if (sum == 0 || sum == 2) Res = "0" + Res;
else if (sum == 1 || sum == 3) Res = "1" + Res;
if (sum == 2 || sum == 3) carry = true;
else carry = false;
}
else throw new Exception("Invalid Input");
}
if (carry) Res = "1" + Res;
return Res;
}
static void Main(string[] args)
{
String A = "1001";
String B = "11010";
Console.WriteLine(Add(A, B));
}
}
}
No comments:
Post a Comment