Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3eb9680

Browse files
Add Binary
1 parent 5446840 commit 3eb9680

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

‎0067_addBinary.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /