Post

[BaekJoon] #2908 - 상수 [Java][C++]

[BaekJoon] #2908 - 상수 [Java][C++]

문제 링크


1. 아이디어

주어진 두 숫자를 거꾸로 읽은 후 더 큰 수를 출력하는 문제로 숫자를 문자열로 입력받아서 뒤집은 후 비교하는 방식으로 해결할 수 있다.


2. 복잡도

접근시간공간
풀이$O(1)$$O(1)$

3. 코드

풀이 [Java][C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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));
        StringTokenizer st = new StringTokenizer(br.readLine());

        String a = new StringBuilder(st.nextToken()).reverse().toString();
        String b = new StringBuilder(st.nextToken()).reverse().toString();

        System.out.println(Math.max(Integer.parseInt(a), Integer.parseInt(b)));
    }
}

StringBuilder의 reverse 메서드를 활용해 주어진 문자열을 뒤집은 후 Integer.parseInt 메서드로 정수로 변환해서 비교했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <bits/stdc++.h>
using namespace std;

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

    string a, b;
    cin >> a >> b;

    reverse(a.begin(), a.end());
    reverse(b.begin(), b.end());

    cout << max(stoi(a), stoi(b));
}

std::reverse 함수로 주어진 문자열을 뒤집은 후 std::stoi 함수로 정수로 변환해서 비교했다.


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