-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.java
More file actions
55 lines (48 loc) · 1.04 KB
/
AddBinary.java
File metadata and controls
55 lines (48 loc) · 1.04 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
package questions100;
public class AddBinary {
public String addBinary(String a, String b) {
// Start typing your Java solution below
// DO NOT write main() function
if (a.isEmpty())
return b;
if (b.isEmpty())
return a;
int i = a.length() - 1, j = b.length() - 1;
int flag = 0, newDigit = 0;
StringBuffer sb = new StringBuffer();
while (i >= 0 || j >= 0) {
int digitA = 0, digitB = 0;
if (i >= 0) {
if (a.charAt(i) == '1')
digitA = 1;
else if (a.charAt(i) == '0')
digitA = 0;
else {
// throw new Exception(
// "Input string has invalid character");
}
}
if (j >= 0) {
if (b.charAt(j) == '1')
digitB = 1;
else if (b.charAt(j) == '0')
digitB = 0;
else {
// throw new Exception(
// "Input string has invalid character");
}
}
int sum = flag + digitA + digitB;
flag = sum / 2;
newDigit = sum % 2;
sb.insert(0, newDigit);
if (i >= 0)
i--;
if (j >= 0)
j--;
}
if (flag == 1)
sb.insert(0, flag);
return sb.toString();
}
}