프로그래머스-문자열 계산하기

남궁진 (jinvicky)·2026년 4월 5일

Problem


https://school.programmers.co.kr/learn/courses/30/lessons/120902

Solution


구조는 맞췄으나 마지막에 temp의 남은 몫에 대한 계산이 없어서 틀린 문제다.

  1. if문은 대략 다음과 같다.
  • 캐릭터가 숫자인 경우
  • 캐릭터가 ' '인 경우
  • 캐릭터가 +, - 와 같은 연산자인 경우
  1. 특정 연산이 2번 반복된다는 특징이 있다.
  • 문자열을 int로 파싱한다.
  • 기존에 저장해 둔 연산자가 없다면 그대로 할당한다.
  • 연산자가 +라면 더한다.
  • 연산자가 -라면 뺀다.
  1. ' '일 때는 연산을 하고 StringBuilder()를 초기화해야 한다.
  • 기존 계산값을 재사용하지 않기 위해서다.
 int v = Integer.parseInt(temp.toString());
               if (oper == ' ') {
                   total = v;
               } else {
                   if(oper == '+') {
                       total += v;
                   } else { // '-'
                       total -= v;
                   }
               }

Code


class Solution {
    public int solution(String my_string) {
       char[] arr = my_string.toCharArray();
    
        int total = 0;
        StringBuilder temp = new StringBuilder();
        char oper = ' ';
        
       for(int i = 0; i < arr.length; i++) {
           if(Character.isDigit(arr[i])) { // 숫자라면 그냥 더한다. 
               temp.append(arr[i]);
           } else if (arr[i] == ' ') {
               if(temp.length() == 0) continue;
               
               int v = Integer.parseInt(temp.toString());
               if (oper == ' ') {
                   total = v;
               } else {
                   if(oper == '+') {
                       total += v;
                   } else { // '-'라는 뜻이다. 
                       total -= v;
                   }
               }
               temp = new StringBuilder();
           } else {
               oper = arr[i]; // 연산자를 저장한다. 
           }
       }
        
        System.out.println(temp);
        
        if(temp.length() > 0) {
            int v = Integer.parseInt(temp.toString());
            
            if(oper == ' ') total = v;
            else if (oper == '+') total += v;
            else total -= v;
        }
        
        return total;
    }
}
profile
문제를 차근차근 하나씩 해결하려고 합니다:)

0개의 댓글