-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.java
More file actions
50 lines (45 loc) · 997 Bytes
/
AddBinary.java
File metadata and controls
50 lines (45 loc) · 997 Bytes
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
package com.mirraico.leetcode;
public class AddBinary {
public String addBinary(String a, String b) {
StringBuilder ans = new StringBuilder();
int[] tmpAns = new int[Math.max(a.length(), b.length()) + 1];
int carry = 0, p = a.length() - 1, q = b.length() - 1, cnt = 0;
while(p >= 0 && q >= 0) {
int tmp = a.charAt(p) - '0' + b.charAt(q) - '0' + carry;
if(tmp > 1) {
tmp -= 2; carry = 1;
} else {
carry = 0;
}
tmpAns[cnt++] = tmp;
p--; q--;
}
while(p >= 0) {
int tmp = a.charAt(p) - '0' + carry;
if(tmp > 1) {
tmp -= 2; carry = 1;
} else {
carry = 0;
}
tmpAns[cnt++] = tmp;
p--;
}
while(q >= 0) {
int tmp = b.charAt(q) - '0' + carry;
if(tmp > 1) {
tmp -= 2; carry = 1;
} else {
carry = 0;
}
tmpAns[cnt++] = tmp;
q--;
}
if(carry == 1) ans.append(1);
for(int i = cnt - 1; i >= 0; i--) {
ans.append(tmpAns[i]);
}
return ans.toString();
}
public static void main(String[] args) {
}
}