Dalyoung 2021. 2. 2. 23:25
728x90
반응형

www.acmicpc.net/problem/1541

 

1541번: 잃어버린 괄호

첫째 줄에 식이 주어진다. 식은 ‘0’~‘9’, ‘+’, 그리고 ‘-’만으로 이루어져 있고, 가장 처음과 마지막 문자는 숫자이다. 그리고 연속해서 두 개 이상의 연산자가 나타나지 않고, 5자리보다

www.acmicpc.net

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
 
public class Main {
    public static void main(String[] args) throws IOException {
        Main m = new Main();
        m.doit();
    }
     
     
     
    public void doit() throws IOException{
       // System.setIn(new FileInputStream("input.txt"));
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int ret = 0;
        String str = br.readLine();
        int index = 0;
        boolean chk = false;
        for(int i = 0; i < str.length(); i++){
        	if(str.charAt(i) == '-' || str.charAt(i) == '+' ){
        		
        		int temp = Integer.parseInt(str.substring(index, i));
        		index = i + 1;
        		if(chk){
        			ret -= temp;
        		}else{
        			ret += temp;
        		}
        		if(str.charAt(i) == '-'){
        			chk = true;
        		}
        			
        	}
        }
        int temp = Integer.parseInt(str.substring(index));
        if(chk){
			ret -= temp;
		}else{
			ret += temp;
		}
        System.out.println(ret);
        
        br.close();
    }
}
728x90
반응형