Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add two numbers in JavaScript "without using `+` or `-` operators"?

Tags:

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 two 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) }; 
like image 378
Microsmsm Avatar asked Jan 04 '17 03:01

Microsmsm


People also ask

How can I add two numbers in JavaScript?

const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.

How can I add without using add operator?

Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc). Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits.

What is the addition symbol in JavaScript?

Addition (+) The addition operator ( + ) produces the sum of numeric operands or string concatenation.


2 Answers

We will use bitwise operators and will use recursion.

We use this method when we have a few low resources. Read more about when to use this method!

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

ECMAScript 6 one-liner solution as suggested by @PatrickRoberts:

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

Another solutions:

2- Arrays technique Array.prototype.fill()

const getSum = (a, b) => {    const firstArr = new Array(a).fill(true);    const secondArr = new Array(b).fill(true);    return firstArr.concat(secondArr).length  }

3- workaround to use plus sign without writing it:

const getSum = (a, b) => eval(''.concat(a).concat(String.fromCharCode(0x2B)).concat(b));
like image 164
Microsmsm Avatar answered Oct 23 '22 08:10

Microsmsm


Well ok i am answering to the question as clearly described in the header. No + and no - operations right..? Yet... not with bitwise but with pure math should be a valid answer i suppose.

var x   = 1,      y   = 2,      sum = Math.log2(2**x * 2**y);  console.log(sum);
like image 24
Redu Avatar answered Oct 23 '22 09:10

Redu