-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd Binary.cs
More file actions
32 lines (29 loc) · 770 Bytes
/
Add Binary.cs
File metadata and controls
32 lines (29 loc) · 770 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
public class Solution {
public string AddBinary(string a, string b) {
if (a == null || b == null) {
return "";
}
var na = a.Length - 1;
var nb = b.Length - 1;
var sb = new StringBuilder();
int carry = 0;
while (na >= 0 || nb >= 0) {
var sum = carry;
if (na >= 0) {
sum += a[na] - '0';
na--;
}
if (nb >= 0) {
sum += b[nb] - '0';
nb--;
}
carry = sum >> 1;
sum = sum & 1;
sb.Insert(0, sum == 0 ? '0' : '1');
}
if (carry > 0) {
sb.Insert(0, '1');
}
return sb.ToString();
}
}