[BaekJoon] #2745 - 진법 변환 [Java][C++][Python]
[BaekJoon] #2745 - 진법 변환 [Java][C++][Python]
1. 아이디어
$B$진법 수 $N$을 10진법으로 바꾸는 문제다. 오른쪽 끝을 0번째라 할 때 $i$번째 자리는 $B^i$의 자리이므로 각 자리의 값에 $B^i$를 곱해 모두 더하면 되며, A부터 Z까지는 10부터 35까지의 값이다. 결과가 10억 이하라 32비트 정수에 담긴다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
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 n = st.nextToken();
int b = Integer.parseInt(st.nextToken());
System.out.println(Integer.parseInt(n, b));
}
}
Integer.parseInt의 두 번째 인자로 진법 b를 넘겨 알파벳 자리까지 한 번에 해석했다.
1
2
3
4
5
6
7
8
9
10
11
12
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
string n;
int b;
cin >> n >> b;
cout << stoi(n, nullptr, b);
}
std::stoi의 세 번째 인자로 진법 b를 넘겼고, 읽은 위치는 필요 없어 두 번째 인자에는 nullptr을 넘겼다.
1
2
3
4
5
6
import sys
input = sys.stdin.readline
n, b = input().split()
print(int(n, int(b)))
int의 두 번째 인자로 진법을 넘겨 문자열을 바로 정수로 바꿨다.
This post is licensed under CC BY 4.0 by the author.