-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathAddBinary.java
40 lines (29 loc) · 897 Bytes
/
AddBinary.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
/*
Source: https://leetcode.com/problems/add-binary/
Time Comlexity : O(max(m, n)), where m and n are the lengths of given Strings a and b respectively.
Space Complexity : O(max(m, n)), as we need a StringBuilder whose size is equal to max of length of 2 input strings
*/
class Solution {
public String addBinary(String a, String b) {
int aLen = a.length() - 1;
int bLen = b.length() - 1;
int maxLen = Math.max(aLen, bLen) + 2;
char[] res = new char[maxLen];
int sum = 0;
while(aLen >= 0 || bLen >= 0) {
if(aLen >= 0 && a.charAt(aLen--) == '1') {
sum += 1;
}
if(bLen >= 0 && b.charAt(bLen--) == '1') {
sum += 1;
}
res[--maxLen] = (char)((sum & 1) + 48);
sum >>= 1;
}
if(sum != 0) {
res[0] = '1';
return String.valueOf(res);
}
return String.valueOf(res, 1, res.length - 1);
}
}