Repository navigation
Expand file tree
/
Copy pathAddBinary.java
More file actions
73 lines (65 loc) · 1.87 KB
/
Copy pathAddBinary.java
File metadata and controls
73 lines (65 loc) · 1.87 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Given two binary strings, return their sum (also a binary string).
// The input strings are both non-empty and contains only characters 1 or 0.
class Solution {
public String addBinary(String a, String b) {
String result = "";
StringBuilder a1 = new StringBuilder();
StringBuilder b1 = new StringBuilder();
a1.append(a);
b1.append(b);
a1 = a1.reverse();
b1 = b1.reverse();
int lena = a1.length();
int lenb = b1.length();
int maxLen = lena;
if(lenb > maxLen){
maxLen = lenb;
}
char c;
boolean carry = false;
for(int i = 0; i < maxLen; i++){
char tempa = '0';
char tempb = '0';
if(i <= lena - 1){
tempa = a1.charAt(i);
}
if(i <= lenb - 1){
tempb = b1.charAt(i);
}
if(tempa == '1' && tempb == '1'){
c = '2';
}else if(tempa == '0' && tempb == '0'){
c = '0';
}else{
c = '1';
}
result = c + result;
}
String str = result;
result = "";
int len = str.length();
carry = false;
for(int i = len - 1; i >= 0; i--){
char index = str.charAt(i);
char temp;
if(carry){
index++;
}
if(index == '2'){
carry = true;
temp = '0';
}else if (index == '3'){
carry = true;
temp = '1';
}else{
temp = index;
carry = false;
}
result = temp + result;
}
if(carry){
result = '1' + result;
}
return result;
}
}