[BaekJoon] 2908번 - 상수 [Java][C++]
[BaekJoon] 2908번 - 상수 [Java][C++]
1. 문제 풀이
주어진 두 숫자를 거꾸로 읽은 후 더 큰 수를 출력하는 문제로 숫자를 문자열로 입력받아서 뒤집은 후 비교하는 방식으로 해결할 수 있다.
2. 코드
1. 풀이 [Java]
StringBuilder의 reverse 메서드를 활용해 주어진 문자열을 뒤집은 후 정수 타입으로 캐스팅해서 비교했다.
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));
}
This post is licensed under CC BY 4.0 by the author.