-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path67-Add-Binary.js
More file actions
39 lines (30 loc) · 783 Bytes
/
67-Add-Binary.js
File metadata and controls
39 lines (30 loc) · 783 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
var addBinary = function(a, b)
{
if( a.length < b.length )
{
a = a.split('').reverse().join('');
while( a.length < b.length )
a += '0';
a = a.split('').reverse().join('');
}
if( a.length > b.length )
{
b = b.split('').reverse().join('');
// console.log(b);
while( b.length < a.length )
b += '0';
b = b.split('').reverse().join('');
}
// console.log(a, b);
let one = 0, ans = '';
for( let i = b.length - 1; i >= 0; i-- )
{
ans += one ^ +a[i] ^ +b[i];
one = (one & +b[i]) || (one & +a[i]) || (+a[i] & +b[i]);
// console.log(one);
}
if( one )
ans += '1';
ans = ans.split('').reverse().join('');
return ans
};