-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathAddBinary.js
54 lines (44 loc) · 1.08 KB
/
AddBinary.js
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
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
// TC: O(1) SC: O(N)
var addBinary = function(a, b) {
return (BigInt(`0b${a}`) + BigInt(`0b${b}`)).toString(2);
};
// TC: O(N) SC: O(1)
var addBinary = function(a, b) {
let lengthA = a.length - 1;
let lengthB = b.length - 1;
let carry = 0;
let result = '';
while (lengthA >= 0 || lengthB >= 0 || carry !== 0) {
const valueA = lengthA >= 0 ? +a[lengthA] : 0;
const valueB = lengthB >= 0 ? +b[lengthB] : 0;
const sum = valueA + valueB + carry;
if(sum === 3) {
carry = 1;
result = '1' + result;
}
else if(sum === 2) {
carry = 1;
result = '0' + result;
}
else if(sum === 1) {
carry = 0;
result = '1' + result;
}
else {
carry = 0;
result = '0' + result;
}
if(lengthA >= 0) {
lengthA--;
}
if(lengthB >= 0) {
lengthB--;
}
}
return result;
};