Skip to content

Commit 7981f56

Browse files
authoredJul 19, 2020
Update 67-add-binary.js
1 parent 1f27625 commit 7981f56

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
 

‎67-add-binary.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,28 @@ const addBinary = function(a, b) {
1616
}
1717
return s
1818
};
19+
20+
// another
21+
22+
/**
23+
* @param {string} a
24+
* @param {string} b
25+
* @return {string}
26+
*/
27+
const addBinary = function(a, b) {
28+
let next = false
29+
let res = []
30+
let ai = a.length - 1
31+
let bi = b.length - 1
32+
while((ai >= 0 && bi >=0) || next) {
33+
const tmp = (ai >= 0 ? +a[ai--] : 0) + (bi >= 0 ? +b[bi--] : 0) + (next ? 1 : 0)
34+
if(tmp > 1) next = true
35+
else next = false
36+
res.unshift('' + (tmp % 2))
37+
}
38+
39+
while(ai >= 0) res.unshift(a[ai--])
40+
while(bi >= 0) res.unshift(b[bi--])
41+
42+
return res.join('')
43+
};

0 commit comments

Comments
 (0)
Please sign in to comment.