-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
39 lines (29 loc) · 954 Bytes
/
Solution.java
File metadata and controls
39 lines (29 loc) · 954 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
package string.sumbin;
/**
* @see <a href="https://leetcode.com/problems/add-binary">Add Binary</a>
*/
public class Solution {
public String addBinary(String number1, String number2) {
StringBuilder sbSum = new StringBuilder();
int index1 = number1.length() - 1;
int index2 = number2.length() - 1;
int carry = 0;
while (index1 >= 0 || index2 >= 0) {
int intermediateSum = carry;
if (index1 >= 0) {
intermediateSum += number1.charAt(index1) - '0';
index1--;
}
if (index2 >= 0) {
intermediateSum += number2.charAt(index2) - '0';
index2--;
}
carry = intermediateSum >> 1;
sbSum.append((intermediateSum & 1) == 1 ? '1' : '0');
}
if (carry > 0) {
sbSum.append('1');
}
return sbSum.reverse().toString();
}
}