PROBLEM 67
Medium

Calculator

Programming Basics · JavaScript

</>
STATUS Not solved

TASK

Problem

#67

Given `a`, operator `op` (`+`, `-`, `*`, `/`), and `b`, print the result. Division always has `b != 0`.

EXAMPLE

Example

Input
8 * 7
Output
56.0

LIMITS

Constraints

op is valid
📖
LEARN Theory for this problem
+

### Calculator

JavaScript arithmetic works with numeric values stored in variables. A clear solution reads the needed values, computes the formula with `+`, `-`, `*`, `/` or `**`, and prints only the final result.

💡
NEED HELP? Hints
+

['Write the formula using named intermediate values if it contains more than one operation.', 'Match each input value type to the operation performed on it: JavaScript string and numeric behavior differ significantly.']

ANSWER Solution
+
const fs = require('fs');
const input = fs.readFileSync(0, 'utf8').trimEnd();
let [a, op, b] = input.trim().split(/\s+/).filter(Boolean);
a = Number(a);
b = Number(b);
if ((op) === ("+")) {
    console.log([(a + b)].map(value => typeof value === 'number' && Number.isInteger(value) ? value.toFixed(1) : String(value)).join(' '));
} else {
    if ((op) === ("-")) {
        console.log([(a - b)].map(value => typeof value === 'number' && Number.isInteger(value) ? value.toFixed(1) : String(value)).join(' '));
    } else {
        if ((op) === ("*")) {
            console.log([a * b].map(value => typeof value === 'number' && Number.isInteger(value) ? value.toFixed(1) : String(value)).join(' '));
        } else {
            console.log([(a / b)].map(value => typeof value === 'number' && Number.isInteger(value) ? value.toFixed(1) : String(value)).join(' '));
        }
    }
}