-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDay-19 Add Binary
50 lines (46 loc) · 1.26 KB
/
Day-19 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public String addBinary(String a, String b) {
char carry = '0';
StringBuilder sb = new StringBuilder();
char[] aCh = a.toCharArray();
char[] bCh = b.toCharArray();
int i = aCh.length-1;
int j = bCh.length-1;
while(i >= 0 || j >= 0) {
char tempA = i >= 0 ? aCh[i] : '0';
char tempB = j >= 0 ? bCh[j] : '0';
if(tempA == tempB) {
if(carry == '0') {
sb.append("0");
}
else {
sb.append('1');
}
carry = tempA;
}
else if(tempA != tempB) {
if(carry == '0') {
sb.append("1");
}
else {
sb.append("0");
carry = '1';
}
}
i--;
j--;
}
if(carry == '1')
sb.append("1");
sb.reverse();
return sb.toString();
}
}
import java.math.BigInteger;
class Solution {
public String addBinary(String a, String b) {
BigInteger x=new BigInteger(a,2);
BigInteger y=new BigInteger(b,2);
return (x.add(y)).toString(2);
}
}