-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0067-add-binary.js
More file actions
34 lines (28 loc) · 898 Bytes
/
0067-add-binary.js
File metadata and controls
34 lines (28 loc) · 898 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
/**
* Add Binary
* Time Complexity: O(max(a.length, b.length))
* Space Complexity: O(max(a.length, b.length))
*/
var addBinary = function (a, b) {
let pointerA = a.length - 1;
let pointerB = b.length - 1;
let carryValue = 0;
const resultDigits = [];
while (pointerA >= 0 || pointerB >= 0 || carryValue === 1) {
let currentDigitA = 0;
if (pointerA >= 0) {
currentDigitA = parseInt(a[pointerA]);
}
let currentDigitB = 0;
if (pointerB >= 0) {
currentDigitB = parseInt(b[pointerB]);
}
const sumIteration = currentDigitA + currentDigitB + carryValue;
const currentResultDigit = sumIteration % 2;
carryValue = Math.floor(sumIteration / 2);
resultDigits.push(currentResultDigit);
pointerA--;
pointerB--;
}
return resultDigits.reverse().join('');
};