-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add Binary.java
55 lines (50 loc) · 1.33 KB
/
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
/*
Given two binary strings, return their sum (also a binary string).
Link: https://leetcode.com/problems/add-binary/
Example: For example,
a = "11"
b = "1"
Return "100".
Solution: None
Source: None
*/
public class Solution {
public String addBinary(String a, String b) {
if (a == null || b == null) {
return "";
}
if (b.length() == 0) {
return a;
}
if (a.length() == 0) {
return b;
}
if (b.length() > a.length()) {
String temp = a;
a = b;
b = temp;
}
int aIndex = a.length() - 1;
int bIndex = b.length() - 1;
int up = 0;
String rst = "";
while (bIndex >= 0) {
int sum = (int)(a.charAt(aIndex) - '0')
+ (int)(b.charAt(bIndex) - '0') + up;
rst = String.valueOf(sum % 2) + rst; // maybe StringBuilder will speed up
up = sum / 2;
aIndex--;
bIndex--;
}
while (aIndex >= 0) {
int sum = (int)(a.charAt(aIndex) - '0') + up;
rst = String.valueOf(sum % 2) + rst;
up = sum / 2;
aIndex--;
}
if (up == 1) {
rst = '1' + rst;
}
return rst;
}
}