R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

{Addition}

Question

Implement a function that adds two numbers without using + or any other built-in arithmetic operators.

Examples

5

+5

10

77

+7

84

00000101

+00000101

00001010

01001101

+00000111

01010100

Approach

5

+5

10

00000101

^00000101

a=00000000

How do you do arithmetic without arithmetic operators? Bitwise operators!

=

00000101

&00000101

00000101

<< 1

b =00001010

=

00000000

^00001010

a=00001010

00000000

&00001010

00000000

<< 1

b =00000000

=

00001010

Solution - Iterative


function add (a, b) {
  while (b !== 0) {
    const uncarried = a ^ b;
    const carries = (a & b) << 1;
    a = uncarried;
    b = carries;
  }
  return a;
}

/* Reseting `a` and `b` like this will ensure we continue 
XOR and AND-ing the new values for the next cycle of the loop */

Solution - Recursive


const add = (a, b) => {
 
  if (b === 0) return a;

  const carried = a ^ b;
  const uncarried = (a & b) << 1;
  return add(carried, uncarried);
}


/* Base case is that there is no more uncarried value.
Otherwise, perform the same operations and return a recursive
call on the carried and uncarried values. */ 

const add = (a, b) => b === 0 ? a : add(a ^ b, (a & b) << 1);

Obnoxious, one-line recursive solution

Reacto: Addition

By Luisa de Miranda