2진수(Binary), 8진수(Octal), 10진수(Decimal), 16진수(Hexadecimal) 등 진법을 변환하는 방법을 정리한다.
10진수를 2, 8, 16 진수로 변환
int a = 10;
// 2진수
System.out.println(Integer.toBinaryString(a));
System.out.println(Integer.toString(a, 2).toUpperCase());
// 8진수
System.out.println(Integer.toOctalString(a));
System.out.println(Integer.toString(a, 8).toUpperCase());
// 16진수
System.out.println(Integer.toHexString(a));
System.out.println(Integer.toString(a, 16).toUpperCase());
// 36진수
System.out.println(Integer.toString(a, 36).toUpperCase());
10진수를 기타 진수로 변환
int a = 35;
// 5진수
System.out.println(Integer.toString(a,5));
// 20진수
System.out.println(Integer.toString(a,20));
// 36진수
System.out.println(Integer.toString(a,36));
N 진수 값을 10진수로 변환
N 진수의 값은 String Type으로 입력해야 한다.
// 2진수 → 10진수
String str = "1111";
System.out.println(Integer.parseInt(str, 2));
// 8진수 → 10진수
str = "17";
System.out.println(Integer.parseInt(str, 8));
// 16진수 → 10진수
str = "F";
System.out.println(Integer.parseInt(str, 16));
// 36진수 → 10진수
str = "Z";
System.out.println(Integer.parseInt(str, 36));
백준 문제 풀이: [2745번] 진법 변환
N 자리수의 숫자가 M 진법으로 표현되어 있을 때, 각 자리수에 M을 자리수 만큼 거듭 제곱한 값을 해당 자리수의 숫자와 곱하여 모두 더하면 10진수가 된다.
- 뒤에서 부터 0번째 자리는 M^0, 1번째 자리는 M^1 순으로 제곱한 값을 숫자의 N번째 자리수에 곱한 후 모두 더한다.
- 2진법 예시: 1001 → (1 × 2^3) + (0 × 2^2) + (0 × 2^1) + (1 × 2^0) = 8 + 0 + 0 + 1 = 9
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
public static void main(String[] args) throws Exception {
st = new StringTokenizer(br.readLine());
String str = st.nextToken();
int rst = 0;
int multiple = 1;
int square = Integer.parseInt(st.nextToken());
for (int i=(str.length()-1); i>=0; i--) {
String tmp = str.substring(i, i+1);
rst += Integer.parseInt(tmp, 36) * multiple;
multiple *= square;
}
System.out.println(rst);
}
}
'CS Fundamentals > Data Structures & Algorithms' 카테고리의 다른 글
[Algorithm] Breadth-First Search (0) | 2025.02.26 |
---|---|
[Data Structures] Collections의 .sort() Method Customize (0) | 2025.02.21 |
[Data Structures] HashMap (0) | 2025.02.19 |
[Data Structures] 자료 구조의 종류와 선택 기준 (0) | 2025.02.19 |
[Data Structures] Variable & Custom Variable (Custom Data Type) (0) | 2025.02.19 |