-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.java
More file actions
39 lines (32 loc) · 950 Bytes
/
AddBinary.java
File metadata and controls
39 lines (32 loc) · 950 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
/**
* Leetcode problem #67, Add Binary
* https://leetcode.com/problems/add-binary/
*
* Time complexity: O(max(n,m))
* Space complexity: O(max(n,m))
*/
public class AddBinary {
public static void main(String[] args) {
String a = "111", b = "11";
String res = addBinary(a, b);
System.out.println(res);
}
public static String addBinary(String a, String b) {
int n = a.length(), m = b.length();
if (n < m)
return addBinary(b, a);
StringBuilder sb = new StringBuilder();
int carry = 0, j = m - 1;
for (int i = n - 1; i > -1; i--) {
if (a.charAt(i) == '1')
++carry;
if (j > -1 && b.charAt(j--) == '1')
++carry;
sb.append((carry % 2 == 1) ? '1' : '0');
carry /= 2;
}
if (carry == 1)
sb.append('1');
return sb.reverse().toString();
}
}