최대 1 분 소요

문제

B진법 수 N이 주어진다. 이 수를 10진법으로 바꿔 출력하는 프로그램을 작성하시오.

10진법을 넘어가는 진법은 숫자로 표시할 수 없는 자리가 있다. 이런 경우에는 다음과 같이 알파벳 대문자를 사용한다.

A: 10, B: 11, …, F: 15, …, Y: 34, Z: 35

입력

첫째 줄에 N과 B가 주어진다. (2 ≤ B ≤ 36)

B진법 수 N을 10진법으로 바꾸면, 항상 10억보다 작거나 같다.

출력

첫째 줄에 B진법 수 N을 10진법으로 출력한다.

문제 링크

https://www.acmicpc.net/problem/2745

난이도: 브론즈 2

알고리즘 분류

  • 수학
  • 구현
  • 문자열

    C++를 사용한 풀이

#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int toNumber(char c){
    int n=0;
    if('0'<=c && c<='9'){
        n=(int)(c-'0');
    }
    else{
        n=(int)(c-'A'+10);
    }
    return n;
}
int toDecimal(string N, int B){
    int answer=0;
    int tmp;
    for(int i=0;i<N.length();++i){
        tmp=toNumber(N[i])* pow(B,N.length()-i-1);
        answer+=tmp;
    }
    return answer;
}

int main(void){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    string N;
    int B;
    cin>>N;
    cin>>B;

    int d=toDecimal(N,B);
    cout<<d<<endl;
}

https://www.acmicpc.net/source/31113900

댓글남기기