-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0067--add-binary.js
36 lines (30 loc) · 927 Bytes
/
0067--add-binary.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
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function (a, b) {
let shortStr = a.length > b.length ? b : a;
let longStr = a.length > b.length ? a : b;
// add zeroes to the shorter string to make its length equal to the longer one
for (let i = shortStr.length; i < longStr.length; i++) {
shortStr = "0" + shortStr;
}
let sum = "";
let carry = 0;
// iterate from the last digit to calculate the sum and carry
for (let i = longStr.length - 1; i >= 0; i--) {
const shortNum = parseInt(shortStr[i]);
const longNum = parseInt(longStr[i]);
const currentSum = shortNum + longNum + carry;
sum = (currentSum % 2) + sum;
carry = Math.floor(currentSum / 2);
}
return carry ? carry + sum : sum;
};
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
const addBinary1 = (a, b) => (BigInt(`0b${a}`) + BigInt(`0b${b}`)).toString(2);