Contents

Calculating strings (with.Java)

   Mar 1, 2024     2 min read

This is an article about the problem of ā€œCalculating stringsā€.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Letā€™s look at the problem first.

problem

my_string is a string formula, such as ā€œ3 + 5ā€.

When the string my_string is given as a parameter, complete the solution function that returns the value calculated by the formula.

Restrictions

  • There are only + and - operators.
  • There are no spaces at the beginning or end of the string.
  • Numbers starting with 0 are not given.
  • Invalid formulas are not given.
  • 5 ā‰¤ length of my_string ā‰¤ 100
  • The result of calculating my_string is between 1 and 100,000.
  • The median calculated value of my_string is between -100,000 and 100,000.
  • The numbers used in calculations are natural numbers between 1 and 20,000.
  • my_string contains at least one operator.
  • The return type is an integer type.
  • The numbers and operators in my_string are separated by a single space.

Input/Output Example

my_stringresult
ā€œ3 + 4ā€7

My solution to the problem

class Solution {
     public int solution(String my_string) {
         String[] strArr = my_string.split(" ");
         int answer = Integer.parseInt(strArr[0]);

         for(int i = 0; i < strArr.length - 1; i++){
             if(strArr[i].equals("+")){
                 answer += Integer.parseInt(strArr[i + 1]);
             }else if(strArr[i].equals("-")){
                 answer -= Integer.parseInt(strArr[i + 1]);
             }
         }
         return answer;
     }
}

Solution explanation

  • The function receives a string as input, separates the string based on spaces, then converts the first value to an integer and sets it as the initial value. Then, through a loop, operators and operands are checked and calculations are performed.
  • If it is the ā€œ+ā€ operator, it adds the next value to the current value.
  • If it is the ā€œ-ā€œ operator, the next value is subtracted from the current value.
  • Returns the final calculated result.
  • This code can be used as a calculator function to perform simple arithmetic operations. For example, if you enter a string like ā€œ10 + 5 - 3ā€, the result will be 10 + 5 - 3 = 12.
  • One thing to note is that there is no logic to verify that the input string is in a valid format, so unexpected behavior may occur if incorrect input is given.