21

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)
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
solimanware
  • 2,952
  • 4
  • 20
  • 40
  • 1
    You're not providing any code or example of what you've tried. You're essentially posting a Comp Sci homework assignment into stack overflow and asking us to solve it for you. You even link to a question that already shows you a method. – erik258 Jan 04 '17 at 03:36
  • 3
    No amount of questions on stack overflow will replace your own study. To really understand the answer, you can't just ask us "how to" solve the problem. You have to attempt to solve it yourself, and if you get stuck, provide the code _and the results_. Take a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators and start learning about bitwise operations. They're essentially the same in just about all languages. Then come back and ask a specific question about the code you wrote when you get stuck. – erik258 Jan 04 '17 at 04:03
  • well the algorithm you copied, you did not copy the recursion.... http://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/ – epascarello Jan 04 '17 at 04:27
  • 1
    `&` = bitwise AND, << = bitwise left shift - and what your getSum function is actually returning is just `(a & b) << 1` - the `a^b` part is not returned and has no effect - that's due to the way the `,` operator works – Jaromanda X Jan 04 '17 at 04:34
  • 2
    @Microsmsm this has been downvoted because it seems pretty clear that you didn't make any effort in producing any try, nor reading a document about JS operators. – Jean-Baptiste Yunès Jan 04 '17 at 09:30
  • One way of doing this job in JS is `var add = (a,b) => b ? add(a^b,(a&b)<<1) : a;` – Redu Jan 05 '17 at 12:31

5 Answers5

19

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));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
solimanware
  • 2,952
  • 4
  • 20
  • 40
  • 1
    `const getSum = (a, b) => b == 0 ? a : getSum(a ^ b, (a & b) << 1);` – Patrick Roberts Aug 21 '17 at 02:14
  • 2
    A very similar one-liner [had been suggested](https://stackoverflow.com/questions/41455750/how-to-add-two-numbers-in-javascript-without-using-or-operators/41456431#comment70175130_41455750) by Redu. – greybeard Jan 10 '18 at 05:06
  • point number 2 will fail in case we have negative numbers eg a = -1, b = 1, result should b 0 – Akshay Bhat May 16 '21 at 15:20
9

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);
Redu
  • 25,060
  • 6
  • 56
  • 76
  • 1
    The accepted answer may only handle 32 bit integers. But this one works for all numbers (with some floating point errors...). – tsh Feb 28 '19 at 06:05
  • 1
    Even with some problems with floating points, this is very original:) I like your solution. – BaseScript Mar 13 '19 at 09:15
2
const add = (a, b) => new Function('a', 'b', `return ${a} ${String.fromCharCode(43)} ${b}`)(a, b);
Constantine
  • 447
  • 4
  • 3
2

It's possible to use arrays structures to perform a sum operation.

function getSum(a, b){
  return Array(a).concat(Array(b)).length / 100;
}

Each input is coerced to an array, for instance, an input of value 5 would be coerced to an array of 5 elements. After coercing both inputs, the arrays are joined into a single array. The length of the final array is returned, by dividing to 100 to deal with the sum of decimal values.

Now, let's try to be defensive about invalid input cases, such as strings or falsy values.

const DEFAULT_NUMBER_VALUE = 0;
const DEFAULT_PRECISION = 100;

function parseAddInput(input){
  if (!input) {
    return DEFAULT_NUMBER_VALUE;
  }
  
  if (typeof input === 'string'){
    input = parseInt(input);
  }
  
  const roundedNumber = Math.round(input * (10 * DEFAULT_PRECISION));
  
  return roundedNumber;
}

function getSum(a, b){
  return Array(
    parseAddInput(a)
  ).concat(
    Array(parseAddInput(b))
  ).length / 100;
}

function add(number1, number2){
  return getSum(number1, number2);
}
Laura Beatris
  • 1,782
  • 7
  • 29
  • 49
1

We can implement same using while loop. We have to shift the carry to left and add it to binary sum of numbers till there will no carry. (As we follows the practice in addition of decimals.)

function getSum(a, b){
  while(b!=0){
    var carry = a&b;  //calculate if is there any carry we need to add
    a = a^b;   // a is used to hold the sum
    b = carry<<1;  //b is used to hold left shift carry
  }
  return a;
}

document.write(getSum(7, 5))
ganesh phirke
  • 471
  • 1
  • 3
  • 12