Problem · Array
Operator-First Array Calculator
Learn this problemProblem statement
Given op equal to "+" or "-" and a non-empty array operands, evaluate the corresponding operator-first expression.
- For
"+", return the sum of every operand. - For
"-", start with the first operand and subtract each later operand from left to right.
Function
calculate(op: String, operands: int[]) → longExamples
Example 1
op = "+"operands = [1,2,3]return = 6The expression is 1 + 2 + 3.
Example 2
op = "-"operands = [10,5,3]return = 2Left-associative subtraction gives (10 - 5) - 3 = 2.
Example 3
op = "-"operands = [-4,-6,3]return = -1The calculation is (-4 - (-6)) - 3 = -1.
Constraints
opis exactly"+"or"-".1 <= operands.length <= 200000.-1000000000 <= operands[i] <= 1000000000.- The final answer fits a signed 64-bit integer.