FastPrepEvaluate a Flat Addition and Subtraction Expression

Evaluate a Flat Addition and Subtraction Expression

Atlassian logoAtlassian● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

Given expression, evaluate its decimal integer additions and subtractions from left to right and return the integer result.

For this exercise, assume the expression is valid and nonempty: an unsigned integer literal followed by zero or more binary + or - operators and unsigned integer literals. ASCII spaces may occur between tokens, and leading zeroes are interpreted as decimal. Unary signs, parentheses, multiplication, division and invalid-input handling are outside this practice contract.

For this exercise, assume a length of at most 500, literals from 0 through 1000000, and all intermediate/final results within signed 32-bit range.

Function

evaluateFlat(expression: String) → int

Examples

Example 1

expression = "3+2-4"return = 1

This authored expression illustrates the reported flat addition/subtraction capability and evaluates to 1.

Example 2

expression = "10 - 20 + 3"return = -7

This authored example has a negative result; spaces occur between tokens.

Example 3

expression = "005 + 12 - 0007"return = 10

This authored example treats leading zeroes as decimal digits.

Constraints

  • For this exercise, assume 1 <= expression.length <= 500.
  • Every literal is a decimal integer from 0 through 1000000.
  • Only binary plus/minus and optional ASCII spaces occur; input is always syntactically valid.
  • All intermediate and final values fit a signed 32-bit integer.

More Atlassian problems

See Atlassian hiring insights
public int evaluateFlat(String expression) {
    // Write your code here.
    return 0;
}
expression"3+2-4"
expected1
Checking account…