[프로그래머스] 문자열 계산하기
2024. 3. 11.

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

조건을 보고 생각해보자.

-연산자는 +,-만 존재

=> 문자열 내에서 +를 찾는 경우 / -를 찾는 경우가 필요하다.

-문자열의 시작과 끝에는 공백이 없다.

=> 공백에 유의하자.

-0으로 시작하는 숫자는 주어지지 않는다.

=>흠..잘 모르겠다. 어떤 고려할 부분을 생각하지 않게 해주는 조건인가?

- 문자열의 길이: 5<=my_string의 길이<= 100

-return type은 정수형

-숫자와 연산자는 공백하나로 구분되어 있다.

 

첫번째 결론: 일단 문자열을 받아서 읽어야하고, +,-연산자를 찾아 경우를 나눠본다.

 

=> 경우를 나누기 위해 문자열 메서드를 다시 정리해보자.

 

IndexOf() : 문자열 내에서 찾고자 하는 문자, 문자열의 위치를 찾음

LastIndexOf() : 찾고자 하는 문자, 문자열의 위치를 뒤에서 부터 찾음

StartsWith() : 지정된 문자열로 끝나는지를 확인

Contains() : 지정된 문자열을 포함하는지를 확인

Replace() :  지정된 두 문자열을 서로 바꾼 새 문자열을 반환

-테스트 케이스는 성공했으나, 채점하니 런타임 에러가 떴다.

=> 특정 조건에서만 동작하는 코드라는 건데.. 왜 안되나 생각해보자.

 

using System;

public class Solution {
    public int solution(string my_string) {
        int answer = 0;
        bool plus;
        bool minus;
        plus = my_string.Contains("+");
        minus = my_string.Contains("-");
        string previous = "";
        string later = "";
        
       if(plus == true){
           var count = my_string.IndexOf("+");
           int i=0;          
           while(i<my_string.Length){
               if(i<count-1)
               {
                 previous += my_string[i];
                 i++;
               }
               else if(i>=count-1&&i<=count+1)
               {
                   i++;
               }
               else if(i>count+1) 
               {                
                   later += my_string[i];
                   i++;
                 
               }
              
           }
         
             int answer1 = Convert.ToInt32(previous);
             int answer2 = Convert.ToInt32(later);
           
              answer = answer1+answer2;
       }
        else if(minus == true){
            var count = my_string.IndexOf("-");
           int i=0;           
           while(i<my_string.Length){
               if(i<count-1)
               {
                 previous += my_string[i];
                 i++;
               }
               else if(i>=count-1&&i<=count+1)
               {
                   i++;
               }
                else if(i>count+1) {              
                   later += my_string[i];
                   i++;
                 
               }
              
           }
         
             int answer1 = Convert.ToInt32(previous);
             int answer2 = Convert.ToInt32(later);
           
              answer = answer1-answer2;
        }
        //else{
          //  answer = 0;
        //}
        return answer;
    }
}

 

myoskin