백준 2745 진법 변환 / C++

이유참치·2025년 12월 15일

백준

목록 보기
90/249

문제 : 2745

풀이 point

진법 변환을 실행하면 된다

36진법의 경우 ZZZZZ :
35364+35363+35362+35361+3536035*36^4 + 35*36^3 + 35*36^2 + 35*36^1 + 35*36^0를 해주면 된다.

풀이 방법

앞서 세운 식으로 코드를 작성한다.
주의할 점은 C++의 경우 cmath헤더의 pow는 부동소수 계산이기 때문에 부동소수 오차가 발생할 수 있다.

코드

//백준 2745, 진법 변환
#include <iostream>
#include <unordered_map>

std::unordered_map<char, int> map;
int main(){

    for(char c = '0'; c <= '9'; ++c){
        map[c] = c - '0';
    }

    for(char c = 'A'; c <= 'Z'; ++c){
        map[c] = 10 + (c - 'A');
    }

    std::string s;
    int B;
    
    std::cin >> s >> B;
    int num{1};
    for(int i{0}; i<s.size()-1; ++i){
        num *= B;
    }
    
    int ans{0};
    for(int i{0}; i<s.size(); ++i){
        auto it = map.find(s[i]);
        int n = it -> second;
        ans += num*n;
        num/=B;
    }

    std::cout << ans;

    return 0;
}
profile
임아리 - 대학생

0개의 댓글