forked from rubythonode/javascript-problems-and-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd-binary.js
More file actions
40 lines (35 loc) · 711 Bytes
/
add-binary.js
File metadata and controls
40 lines (35 loc) · 711 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
36
37
38
39
40
/**
* Add Binary
*
* Given two binary strings, return their sum (also a binary string).
*
* The input strings are both non-empty and contains only characters 1 or 0.
*
* Example 1:
*
* Input: s1 = "11", s2 = "1"
* Output: "100"
* Example 2:
*
* Input: s1 = "1010", s2 = "1011"
* Output: "10101"
*/
/**
* @param {string} s1
* @param {string} s2
* @return {string}
*/
const addBinary = (s1, s2) => {
let i = s1.length - 1;
let j = s2.length - 1;
let c = 0;
let s = '';
while (i >= 0 || j >= 0 || c > 0) {
const a = i < 0 ? 0 : s1[i--] - '0';
const b = j < 0 ? 0 : s2[j--] - '0';
s = (a ^ b ^ c) + s;
c = (a + b + c) >> 1;
}
return s;
};
export { addBinary };