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:
^
&
<<
, 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) };
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.
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.
Addition (+) The addition operator ( + ) produces the sum of numeric operands or string concatenation.
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));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With