- Related Questions & Answers
- MySQL query to select ENUM('M', 'F') as 'Male' or 'Female'?
- Update 'a' record with 'b' and 'b' with 'a' in a MySQL column (swap) with only 'a' and 'b' values?
- What is difference between '.' , '?' and '*' in Python regular expression?
- Write the main difference between '==' and '===' operators in javascript?
- Replace '*' with '^' with Java Regular Expressions
- Program to find number of string we can make where 'a' can be 'a' or 'b', and 'b' remains 'b'in Python
- what is the main difference between '=' and '==' operators in javascript?
- How and why does 'z'['toUpperCase']() in JavaScript work?
- Why JavaScript 'var null' throw an error but 'var undefined' doesn't?
- The difference between 'AND' and '&&' in MySQL?
- Difference between 'struct' and 'typedef struct' in C++?
- What is the difference between 'isset()' and '!empty()' in PHP?
- What is the difference between 'log' and 'symlog' in matplotlib?
- Difference between 'struct' and 'typedef struct' in C++ program?
- How to Use 'U' and 'L' formatters in Arduino?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

We are required to write a JavaScript function add() that takes in two numbers m and n. The function should, without using the four basic arithmetic operations add the two numbers taken as input and return the sum.

The code for this will be −

const m = 67, n = 33; const add = (x, y) => { while(y !== 0){ let carry = x & y; x = x ^ y; y = carry << 1; }; return x; }; console.log(add(m, n));

Sum of two bits can be obtained by performing XOR (^) of the two bits. And the carry bit can be obtained by performing AND (&) of two bits.

We have here used an extended version of the Half Adder logic that can be used to add 2 single bits to add two integers. If x and y don’t have set bits at the same position(s), then bitwise XOR (^) of x and y gives the sum of x and y.

To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We have calculated (x & y) << 1 and added it to x ^ y to get the required result.

And the output in the console will be −

100

Advertisements