[BOJ][2745] 진법 변환
Updated:
1. 문제 링크
https://www.acmicpc.net/problem/2745
2. 사용 알고리즘
수학
3. 풀이
B진법 수 N을 10진수로 변환
EX) 3진법 102를 10진수로 변환하는 경우
-
ans = 1
-
ans = (1 * 3) + 0
-
ans = (1 * 3 + 0) * 3 + 2
4. 소스 코드
4-1. C++
https://github.com/dev-aiden/problem-solving/blob/main/boj/2745.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int main(void) {
ios_base::sync_with_stdio(false);
string n; int b; cin >> n >> b;
int len = n.length();
int ans = 0;
for (int i = 0; i < len; ++i) {
int num = n[i] >= 65 ? n[i] - 55 : n[i] - 48;
ans *= b;
ans += num;
}
cout << ans << "\n";
return 0;
}
4-2. JAVA
https://github.com/dev-aiden/problem-solving/blob/main/boj/2745.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
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());
int n = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
StringBuilder ans = new StringBuilder();
while (n != 0) {
int temp = n % b;
if (temp < 10) ans.append((char)(temp + 48));
else ans.append((char)(temp + 55));
n /= b;
}
ans.reverse();
System.out.println(ans);
}
}
Leave a comment