|
| 1 | +/** |
| 2 | + * @param {string} a String representing a binary number. |
| 3 | + * @param {string} b String representing a binary number. |
| 4 | + * @return {string} String representing a binary number being sum of both parameters. |
| 5 | + * @summary Add Binary {@link https://leetcode.com/problems/add-binary/} |
| 6 | + * @description Given a two binary numbers represented by a string, return their sum. |
| 7 | + * Space O(MaxOf(A, B)) - keeping the answer in separate string/array - A, B being length of input strings. |
| 8 | + * Time O(MaxOf(A, B)) - for amount of steps in iteration - A, B being length of input strings. |
| 9 | + */ |
| 10 | +const addBinary = (a, b) => { |
| 11 | + const binaryA = a.split('').reverse().join(''); |
| 12 | + const binaryB = b.split('').reverse().join(''); |
| 13 | + |
| 14 | + const length = Math.max(binaryA.length, binaryB.length); |
| 15 | + const result = []; |
| 16 | + let carryOver = 0; |
| 17 | + |
| 18 | + for (let index = 0; index < length; index++) { |
| 19 | + let numberA = +binaryA[index] || 0; |
| 20 | + let numberB = +binaryB[index] || 0; |
| 21 | + |
| 22 | + let sum = numberA + numberB + carryOver; |
| 23 | + result.unshift(sum % 2); |
| 24 | + |
| 25 | + carryOver = sum > 1 ? 1 : 0; |
| 26 | + } |
| 27 | + |
| 28 | + if (carryOver) result.unshift(carryOver); |
| 29 | + |
| 30 | + return result.join(''); |
| 31 | +}; |
| 32 | + |
| 33 | +// onliner using 0b notation and BigInt |
| 34 | +// const addBinary = (a, b) => (BigInt('0b' + a) + BigInt('0b' + b)).toString(2); |
0 commit comments