-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.cs
More file actions
46 lines (36 loc) · 999 Bytes
/
Copy pathAddBinary.cs
File metadata and controls
46 lines (36 loc) · 999 Bytes
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCodeSolutions.LeetCodeProblems
{
/*
Given two binary strings a and b, return their sum as a binary string.
Example:
Input: a = "11", b = "1"
Output: "100"
*/
public class AddBinary
{
public string AddBinarySolution(string a, string b)
{
string result = "";
int i = a.Length - 1;
int j = b.Length - 1;
int sum, carry = 0;
while(i >= 0 || j >= 0)
{
sum = carry;
if(i >= 0) sum += a[i] - '0';
if(j >= 0) sum += b[j] - '0';
result += (sum % 2).ToString();
carry = sum / 2;
i--;
j--;
}
if (carry != 0) result += '1';
return new string(result.Reverse().ToArray());
}
}
}