FastPrepReal-Number Calculator

Real-Number Calculator

NVIDIA logoNVIDIA● EasyINTERNPHONE SCREEN

Problem statement

Implement a calculator for real numbers. For this exercise, assume each request contains two operands, left and right, and one arithmetic operation operation.

  • "+": return left + right.
  • "-": return left - right.
  • "*": return left * right.
  • "/": return left / right using real-number division.

For this exercise, assume every request is valid: the operation is one of these four symbols, and a division request has a nonzero divisor. Evaluate just this one operation; there is no expression string to parse.

Return a double-precision result. An answer is accepted when its absolute error is at most 10^-6 * max(1, abs(expected)). Do not round the answer to a fixed number of decimal places.

Function

calculateReal(left: double, operation: String, right: double) → double

Examples

Example 1

left = 2.5operation = "+"right = 1.75return = 4.25

Adding 2.5 and 1.75 gives 4.25.

Example 2

left = -3.5operation = "-"right = 2return = -5.5

Subtracting 2 from -3.5 gives -5.5.

Example 3

left = 1.2operation = "*"right = -2.5return = -3

Multiplying 1.2 by -2.5 gives -3.

Example 4

left = 7.5operation = "/"right = 2return = 3.75

Real-number division gives 7.5 / 2 = 3.75.

Constraints

  • -10^6 <= left <= 10^6.
  • -10^6 <= right <= 10^6.
  • Both operands are finite real numbers.
  • operation.length == 1, and operation is one of "+", "-", "*", or "/".
  • When operation == "/", abs(right) >= 10^-6.

More NVIDIA problems

See NVIDIA hiring insights
Saved
public double calculateReal(double left, String operation, double right) {
    // Write your code here.
}
Checking account…