-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsolution.ts
More file actions
35 lines (28 loc) · 756 Bytes
/
solution.ts
File metadata and controls
35 lines (28 loc) · 756 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
35
/*
* @lc app=leetcode id=67 lang=javascript
*
* [67] Add Binary
*/
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
const addBinary = (a: string, b: string): string => {
if (a === '' && b === '') return '0';
const maxLen = Math.max(a.length, b.length);
const aRemainLen = a.length - maxLen;
const bRemainLen = b.length - maxLen;
let result = '';
let carry = 0;
for (let point = maxLen - 1; point >= 0; point--) {
const aCarry = Number(a[aRemainLen + point] || 0);
const bCarry = Number(b[bRemainLen + point] || 0);
const subSum = aCarry + bCarry + carry;
carry = subSum >> 1;
result = (subSum % 2) + result;
}
if (carry) result = '1' + result;
return result;
};
export { addBinary };