Post

[BaekJoon] #1550 - 16진수 [Java][C++][Python]

[BaekJoon] #1550 - 16진수 [Java][C++][Python]

문제 링크


1. 아이디어

16진수 수를 10진수로 바꿔 출력한다. 각 자리의 값(A~F는 10~15)에 그 자리의 16의 거듭제곱을 곱해 모두 더하면 10진수 값이 되고, 최대 6글자라 $16^6 - 1 = 16{,}777{,}215$ 이하여서 32비트 정수에 들어간다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
8
9
10
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String s = br.readLine();
        System.out.println(Integer.parseInt(s, 16));
    }
}

Integer.parseInt의 두 번째 인자로 진법 16을 넘겨 문자열을 바로 정수로 바꿨다.

1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    string s;
    cin >> s;
    cout << stoi(s, nullptr, 16);
}

std::stoi의 세 번째 인자로 진법 16을 넘겼고, 읽은 위치는 필요 없어 두 번째 인자에는 nullptr을 넘겼다.

1
2
3
4
5
6
import sys

input = sys.stdin.readline

s = input().rstrip()
print(int(s, 16))

int의 두 번째 인자로 진법 16을 넘겨 문자열을 바로 정수로 바꿨다.


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