JavaScript: Check whether it is possible to replace $ in a specified expression
JavaScript Basic: Exercise-89 with Solution
Write a JavaScript program to check whether it is possible to replace $ in a given expression x $ y = z with one of the four signs +, -, * or / to obtain a correct expression.
For example x = 10, y = 30 and z = 300, we can replace $ with a multiple operator (*) to obtain x * y = z
Visual Presentation:
Sample Solution:
JavaScript Code:
// Function to check if there is an arithmetic expression (addition, multiplication, division, or subtraction) among three numbers
function check_arithmetic_Expression(x, y, z) {
// Check if any of the arithmetic expressions holds true
return x + y == z || x * y == z || x / y == z || x - y == z;
}
// Examples of using the function
console.log(check_arithmetic_Expression(10, 25, 35)); // true, as 10 + 25 = 35
console.log(check_arithmetic_Expression(10, 25, 250)); // true, as 10 * 25 = 250
console.log(check_arithmetic_Expression(30, 25, 5)); // true, as 30 / 25 = 1.2
console.log(check_arithmetic_Expression(100, 25, 4.0)); // true, as 100 / 25 = 4.0
console.log(check_arithmetic_Expression(100, 25, 25)); // true, as 100 - 25 = 75
Output:
true true true true false
Live Demo:
See the Pen javascript-basic-exercise-89 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
// Function to check if any of the arithmetic expressions (addition, multiplication, division, subtraction) is true
const check_arithmetic_Expression = (x, y, z) => {
// Return true if any of the arithmetic expressions is true
return x + y == z || x * y == z || x / y == z || x - y == z;
};
// Example usage
console.log(check_arithmetic_Expression(10, 25, 35)); // true
console.log(check_arithmetic_Expression(10, 25, 250)); // true
console.log(check_arithmetic_Expression(30, 25, 5)); // true
console.log(check_arithmetic_Expression(100, 25, 4.0)); // true
console.log(check_arithmetic_Expression(100, 25, 25)); // false
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program that takes two integers and a divisor. If the given divisor divides both integers and it does not divide either, then two given integers are similar. Check whether two given integers are similar or not.
Next: JavaScript program to find the kth greatest element of a given array of integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/javascript-basic-exercise-89.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics