How to add two numbers in Javascript "without using `+` or `-` operators"?

Question

Update:

This is NOT a basic "how to add numbers in JavaScript" question

Please read the question carefully before downvoting

I know an alternative to using the + sign for addition is to do something like this:

int add(int a, int b)
{
     if(b == 0)
         return sum;
     sum = a ^ b;
     carry = (a & b) << 1;
     return add(sum,carry);
}

But I have 2 problems:

  • This is C++, not JavaScript. Is this supported in JavaScript?
  • It's obvious the whole trick is in ^ & <<, but I don't know how to start looking for them in JavaScript, because I don't know what they are called.
    What should I be googling for even?

I tried to write this in JavaScript ... but seems I miss something

var getSum = function(a, b) {
  return (a ^ b, (a & b) << 1)
};

Show source
| javascript   | algorithm   2017-01-04 04:01 1 Answers

Answers to How to add two numbers in Javascript &quot;without using `+` or `-` operators&quot;? ( 1 )

  1. 2017-01-04 05:01

    We will use bitwise operators that's how we call them

    You use this method when you have low resources

    var getSum = function(a, b) {
        if (b == 0) {
            return a;
        } else {
            return getSum(a ^ b, (a & b) << 1)
        }
    };

Leave a reply to - How to add two numbers in Javascript "without using `+` or `-` operators"?

◀ Go back