-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add Binary
31 lines (31 loc) · 977 Bytes
/
Add Binary
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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(a == null || b == null)
return null;
String result = "";
if(a.isEmpty() || b.isEmpty())
return result;
return helpler(result, a, b);
}
private String helpler(String result, String a, String b)
{
int carrier = 0;
int m = a.length()-1;
int n = b.length()-1;
for(int i=0; i<=Math.max(m, n); i++)
{
int c_a = (m>=i) ? a.charAt(m-i)-'0' : 0;
int c_b = (n>=i) ? b.charAt(n-i)-'0' : 0;
result = (c_a+c_b+carrier)%2 + result;
carrier = (c_a+c_b+carrier)/2;
}
if(carrier == 0)
return result;
else{
result = "1"+result;
return result;
}
}
}