-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0067. Add Binary
69 lines (68 loc) · 2 KB
/
0067. 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class Solution {
// public String addBinary(String a, String b) {
// StringBuilder sb = new StringBuilder();
// int i = a.length() - 1;
// int j = b.length() - 1;
// int one = 0;
// while(i > -1 || j > -1) {
// int sum = one;
// if(i > -1) {
// sum += (a.charAt(i) - '0');
// }
// if(j > -1) {
// sum += (b.charAt(j) - '0');
// }
// if(sum >= 2) {
// sum -= 2;
// one = 1;
// }
// else {
// one = 0;
// }
// sb.insert(0, String.valueOf(sum));
// if(i > -1) {
// i--;
// }
// if(j > -1) {
// j--;
// }
// }
// if(one == 1) {
// sb.insert(0, '1');
// }
// return sb.toString();
// }
public String addBinary(String a, String b) {
int i = a.length() - 1;
int j = b.length() - 1;
int one = 0;
StringBuilder sb = new StringBuilder();
for (; i > -1 && j > -1; i--, j--) {
int curr = a.charAt(i) - '0' + b.charAt(j) - '0' + one;
one = (curr > 1 ? 1 : 0);
curr = curr % 2;
sb.append(curr);
}
if (i == -1 && j != -1) {
for (; j > -1; j--) {
int curr = b.charAt(j) - '0' + one;
one = (curr > 1 ? 1 : 0);
curr = curr % 2;
sb.append(curr);
}
}
if (i != -1 && j == -1) {
for (; i > -1; i--) {
int curr = a.charAt(i) - '0' + one;
one = (curr > 1 ? 1 : 0);
curr = curr % 2;
sb.append(curr);
}
}
if (one == 1) {
sb.append('1');
}
sb.reverse();
return sb.toString();
}
}