-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJuly19_2020.java
49 lines (35 loc) · 1.09 KB
/
July19_2020.java
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
// Add String given in Binary style
class Solution {
public String addBinary(String a, String b) {
int lenA = a.length()-1;
int lenB = b.length()-1;
int flag = 0;
StringBuilder sb = new StringBuilder();
while(lenA >= 0 || lenB >=0) {
int valA = 0;
int valB = 0;
if(lenA >= 0) {
valA = a.charAt(lenA) == '0' ? 0 : 1;
lenA--;
}
if(lenB >= 0) {
valB = b.charAt(lenB) == '0' ? 0 : 1;
lenB--;
}
int result = valA + valB + flag;
if(result >= 2) {
sb.append(String.valueOf(result-2));
flag = 1;
}
else {
sb.append(String.valueOf(result));
flag = 0;
}
}
if(flag == 1){
sb.append("1");
}
String finalResult = sb.reverse().toString();
return finalResult;
}
}