Subtract Two Numbers Without Using the Sign in JavaScript



We are required to write a JavaScript function that takes in two numbers and returns their difference but without using the (-) sign

Example

Following is the code −

const num1 = 56;
const num = 78;
const subtractWithoutMinus = (num1, num2) => {
   if(num2 === 0){
      return num1;
   };
   return subtractWithoutMinus(num1 ^ num2, (~num1 & num2) << 1);
};
console.log(subtractWithoutMinus(num, num1));

Output

Following is the output in the console −

22
Updated on: 2020-09-18T08:58:01+05:30

298 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements