binary addition javascript

Solutions on MaxInterview for binary addition javascript by the best coders in the world

showing results for - "binary addition javascript"
Simone
18 Aug 2019
1function binaryAddition(a,b){
2  var result = "",
3      carry = 0;
4
5  while(a || b || carry){
6    let sum = +a.slice(-1) + +b.slice(-1) + carry; // get last digit from each number and sum 
7
8    if( sum > 1 ){  
9      result = sum%2 + result;
10      carry = 1;
11    }
12    else{
13      result = sum + result;
14      carry = 0;
15    }
16    
17    // trim last digit (110 -> 11)
18    a = a.slice(0, -1)
19    b = b.slice(0, -1)
20  }
21  
22  return result;
23}
24
25// Tests
26[
27  ["0","0"],
28  ["1","1"],
29  ["1","0"],
30  ["0","1"],
31  ["10","1"],
32  ["11","1"],
33  ["10","10"],
34  ["111","111"],
35  ["1010","11"]
36].forEach(numbers => 
37   document.write(
38     numbers[0] + " + " + 
39     numbers[1] + " = " + 
40     binaryAddition(numbers[0], numbers[1]) + 
41     "      <mark> (" +
42     parseInt(numbers[0], 2) + " + " + 
43     parseInt(numbers[1], 2) + " = " + 
44     parseInt(binaryAddition(numbers[0], numbers[1]),2) +
45     ")</mark><br>" 
46   )
47)
48document.body.style="font:16px monospace";