백준 1541 자바 및 C++

이진우·2023년 9월 21일

알고리즘 문제풀이

목록 보기
34/95

풀기 전:

특정한 규칙을 발견해야 한다.

이 문제의 규칙은 -가 한번이라도 등장하게 된다면...

그 뒤에 나오는 +를 모두 -로 괄호로 바꿀 수 있게 된다.

그렇게 되면 뒤의 -값이 커져서 최소로 만들 수 있게 된다.

따라서 처음부터 연속된 +값들은 다 더해주고 -가 한번이라도 나온 순간 그 뒤에 나오는 연산자가 어떤 것이든 다 빼주면 된다.

자바(JAVA)

import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.util.Collections;
public class Main{
    public static void main(String[] args) throws IOException {
      Scanner scanner=new Scanner(System.in);
      String s=scanner.next();
      boolean showMinus=false;
      int total=0;
      int startIndex=0;
      int endIndex=0;
      for(int i=0;i<s.length();i++){
          if(s.charAt(i)>='0'&&s.charAt(i)<='9'){
              if(i==s.length()-1){
                  String stringTmp=s.substring(startIndex,s.length());
                  int intTmp=0;
                  int zari=1;
                  for(int j=stringTmp.length()-1;j>=0;j--){
                      intTmp+=(stringTmp.charAt(j)-'0')*zari;
                      zari*=10;
                  }
                  if(!showMinus){
                      total+=intTmp;
                  }
                  else{
                      total-=intTmp;
                  }
              }
              endIndex++;
          }
          else{
              String stringTmp=s.substring(startIndex,endIndex);
              int intTmp=0;
              int zari=1;
              for(int j=stringTmp.length()-1;j>=0;j--){
                  intTmp+=(stringTmp.charAt(j)-'0')*zari;
                  zari*=10;
              }
              if(!showMinus){
                  total+=intTmp;
              }
              else{
                  total-=intTmp;
              }
              startIndex=i+1;
              endIndex=startIndex;
              if(s.charAt(i)=='-'){
                  showMinus=true;
              }
          }

      }
      System.out.println(total);
    }
}

C++

#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <string>
using namespace std;
int main(void) { 
	string s;
	cin >> s;
	bool showMinus = false;
	int total = 0;
	int startIndex = 0;
	int endIndex = 0;
	for (int i = 0; i < s.length(); i++) {
		if (s[i] >= '0' && s[i] <= '9') {
			if (i == s.length() - 1) {
				string stringTmp = s.substr(startIndex, s.length() - startIndex);
				int intTmp = 0;
				int zari = 1;
				for (int j = stringTmp.length() - 1; j >= 0; j--) {
					intTmp += (stringTmp[j] - '0') * zari;
					zari *= 10;
				}
				if (!showMinus) {
					total += intTmp;
				}
				else {
					total -= intTmp;
				}
			}
			endIndex++;
		}
		else {
			string stringTmp = s.substr(startIndex, endIndex-startIndex);
			int intTmp = 0;
			int zari = 1;
			for (int j = stringTmp.length() - 1; j >= 0; j--) {
				intTmp += (stringTmp[j] - '0') * zari;
				zari *= 10;
			}
			if (!showMinus) {
				total += intTmp;
			}
			else {
				total -= intTmp;
			}
			startIndex = i + 1;
			endIndex = startIndex;
			if (s[i] == '-') {
				showMinus = true;
			}
		}
	}

	cout << total;
}

6개월 후에 다시 풀었을 때:
규칙을 아예 오해했었다. 먼저 검증을 하고 그 다음에 코드로 옮기는 과정이 필요하겠다. 무턱대고 코드부터 만들지 말고.

import java.io.*;
import java.lang.reflect.Array;
import java.nio.Buffer;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
       Scanner scanner=new Scanner(System.in);

       String fullSentence=scanner.nextLine();
       int sum=0;
       String tmpNum="";
       boolean minusPresent=false;
       for(int i=0;i<fullSentence.length();i++) {
           if (fullSentence.charAt(i) == ('+')||fullSentence.charAt(i)=='-') {
               int a=Integer.parseInt(tmpNum);
               if(minusPresent){
                   sum-=a;
               }
               else{
                  sum+=a;
               }
               if(fullSentence.charAt(i)=='-'){
                  minusPresent=true;
               }
               tmpNum="";
           }
           else {
               tmpNum += fullSentence.charAt(i);
           }
       }
        int a=Integer.parseInt(tmpNum);
        if(minusPresent){
            sum-=a;
        }
        else{
            sum+=a;
        }
        System.out.println(sum);



    }


}

String 을 int로 바꿔주는 것을 이용 더욱 편하게 푼 것같다.

profile
기록을 통해 실력을 쌓아가자

0개의 댓글