-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAddBinary.cs
54 lines (42 loc) · 1.14 KB
/
AddBinary.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCodeProblems
{
internal static class AddBinary
{
public static void Test()
{
// Given two binary strings a and b, return their sum as a binary string.
Console.WriteLine(AddBinary1("11", "1"));
Console.WriteLine(AddBinary1("1010", "1011"));
}
public static string AddBinary1(string a, string b)
{
var i = a.Length - 1;
var j = b.Length - 1;
var carry = 0;
var result = "";
while (i >= 0 || j >= 0 || carry > 0)
{
var sum = carry;
if (i >= 0)
{
sum += a[i] - '0';
i--;
}
if (j >= 0)
{
sum += b[j] - '0';
j--;
}
result = (sum % 2) + result;
carry = sum / 2;
}
return result;
}
}
}