- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding the sum of two numbers without using '+', '-', '/', '*' in JavaScript
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.
Example
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));
Explanation
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.
Output
And the output in the console will be −
100