Post

[백준] 2908번 - 상수 [Java][C++]

[백준] 2908번 - 상수 [Java][C++]

문제 링크


1. 문제 풀이

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


2. 코드

1. 구현 [Java]

StringBuilderreverse 메서드를 활용해 주어진 문자열을 뒤집은 후 정수 타입으로 캐스팅해서 비교했다.

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 revA = new StringBuilder(st.nextToken()).reverse().toString();
        String revB = new StringBuilder(st.nextToken()).reverse().toString();

        System.out.println(Math.max(Integer.parseInt(revA), Integer.parseInt(revB)));
    }
}

2. 구현 [C++]

reverse 함수로 주어진 문자열을 뒤집은 후 stoi 함수로 정수 타입으로 캐스팅해서 비교했다.

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(false);
    cin.tie(nullptr);

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

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

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

3. 풀이 정보

1. 구현 [Java]

언어시간메모리코드 길이
Java 11104 ms14248 KB522 B

2. 구현 [C++]

언어시간메모리코드 길이
C++ 170 ms2024 KB257 B

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