Skip to content

Instantly share code, notes, and snippets.

@y0n1
Last active March 24, 2024 13:31
Show Gist options
  • Save y0n1/7ddaba40ccdd741b6ae44e1b28c2da1c to your computer and use it in GitHub Desktop.
Save y0n1/7ddaba40ccdd741b6ae44e1b28c2da1c to your computer and use it in GitHub Desktop.
Given a string of an arithmetic expression; which includes only two operators: '+', '*' , write a function that evaluates the expression and returns its result.Input: A (possible) very long string of an arithmetic expression: "1*2*3+1+20".Output: 27
public class Solution {
public static void main(String[] args) {
String[] input = { "5", "4+20*3", "20*3+4", "20+20+20+4", "4*4*4" };
for (String test : input)
System.out.printf("%s = %d%n", test, eval(test));
}
private static int eval(String input) {
int sum = 0;
int multiplication = 1;
String currentNumber = "";
if (input.matches("\\d+"))
return Integer.parseInt(input);
for (int i = 0; i < input.length(); i++) {
char currentChar = input.charAt(i);
switch (currentChar) {
case '+':
sum += multiplication * Integer.parseInt(currentNumber);
multiplication = 1;
currentNumber = "";
break;
case '*':
multiplication *= Integer.parseInt(currentNumber);
currentNumber = "";
break;
default:
currentNumber += currentChar;
break;
}
}
return sum += multiplication * Integer.parseInt(currentNumber);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment