JavaScript: Subtract without arithmetic operators
JavaScript Math: Exercise-76 with Solution
Write a JavaScript program to subtract one integer from another, without using arithmetic operators such as -, %, /, +, etc.
Test Data:
(200, 100) -> 100
(200, 300) -> -100
(-200, -300) -> 100
(200, 200) -> 0
Sample Solution:
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript program to Subtract without arithmetic operators</title>
</head>
<body>
</body>
</html>
JavaScript Code:
function test1(a, b)
{
do
{
let temp = (~a) & b;
a = a ^ b;
b = temp << 1;
}while (b != 0)
return a;
}
console.log(test1(200, 100));
console.log(test1(200, 300));
console.log(test1(-200, -300));
console.log(test1(200, 200));
Sample Output:
100 -100 100 0
Flowchart:

Live Demo:
See the Pen javascript-math-exercise-76 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Swap three numbers.
Next: Two positive integers as string, return their sum.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join