-
Notifications
You must be signed in to change notification settings - Fork 0
/
67.add-binary.java
93 lines (87 loc) · 2.23 KB
/
67.add-binary.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class Solution {
public String addBinary(String a, String b) {
StringBuilder str = new StringBuilder();
int i = a.length()-1;
int j = b.length()-1;
char carr = 0;
while(i >= 0 && j >= 0 ){
int curr = valOf(a.charAt(i))+valOf(b.charAt(j))+carr;
// System.out.println(curr);
if(curr == 1){
str.append('1');
carr = 0;
}
else if(curr == 2){
str.append('0');
carr = 1;
}
else if(curr == 3){
str.append('1');
carr = 1;
}
else if(carr == 1){
str.append('1');
curr = 0;
}
else{
str.append('0');
}
j--;
i--;
}
while(i >= 0){
int curr = valOf(a.charAt(i))+(int)carr;
if(curr == 1){
str.append('1');
carr = 0;
}
else if(curr == 2){
str.append('0');
carr = 1;
}
else if(curr == 3){
str.append('1');
carr = 1;
}
else if(carr == 1){
str.append('1');
curr = 0;
}
else{
str.append('0');
}
i--;
}
while(j >= 0){
int curr = valOf(b.charAt(j))+(int)carr;
if(curr == 1){
str.append('1');
carr = 0;
}
else if(curr == 2){
str.append('0');
carr = 1;
}
else if(curr == 3){
str.append('1');
carr = 1;
}
else if(carr == 1){
str.append('1');
curr = 0;
}
else{
str.append('0');
}
j--;
}
if(carr == 1)
str.append('1');
return str.reverse().toString();
}
public int valOf(Character c){
if(c == '1')
return 1;
return 0;
}
}