Post

[BaekJoon] #5355 - 화성 수학 [Java][C++][Python]

[BaekJoon] #5355 - 화성 수학 [Java][C++][Python]

문제 링크


1. 아이디어

수에 연산자를 왼쪽부터 차례로 적용하는 문제로, @는 3을 곱하고 %는 5를 더하며 #는 7을 뺀다. 수가 소수 첫째 자리까지 주어지고 세 연산 모두 소수 첫째 자리를 넘기지 않으므로 결과도 소수 첫째 자리까지이고, 소수점 둘째 자리는 항상 0이다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import java.io.*;
import java.util.*;

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

        int t = Integer.parseInt(br.readLine());
        while (t-- > 0) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            double x = Double.parseDouble(st.nextToken());

            while (st.hasMoreTokens()) {
                char op = st.nextToken().charAt(0);
                if (op == '@') {
                    x *= 3;
                } else if (op == '%') {
                    x += 5;
                } else {
                    x -= 7;
                }
            }

            System.out.printf("%.2f\n", x);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int t;
    cin >> t >> ws;

    while (t--) {
        string line;
        getline(cin, line);
        stringstream ss(line);

        double x;
        ss >> x;

        char op;
        while (ss >> op) {
            if (op == '@') {
                x *= 3;
            } else if (op == '%') {
                x += 5;
            } else {
                x -= 7;
            }
        }

        cout << fixed << setprecision(2) << x << '\n';
    }
}

t를 읽은 뒤 남은 줄바꿈을 std::ws로 건너뛰어, 첫 std::getline이 빈 줄을 읽지 않게 했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import sys

input = sys.stdin.readline

t = int(input())
for _ in range(t):
    tokens = input().split()
    x = float(tokens[0])

    for op in tokens[1:]:
        if op == "@":
            x *= 3
        elif op == "%":
            x += 5
        else:
            x -= 7

    print(f"{x:.2f}")

This post is licensed under CC BY 4.0 by the author.