본문 바로가기
공부기록/[Algorithm]

백준 2745번 <진법 변환> - C++

by RiverWon 2024. 8. 7.

생각


1. 숫자와 문자가 혼용되어 입력으로 들어오니, string으로 받은 다음 하나씩 처리하자

2. 숫자, 알파벳 둘 다 문자로 취급하니까 아스키코드 범위 내에서 적정 값을 빼서, int형태의 배열에 넣자

숫자 값으로 변형 완료

3. 각 배열에 들어있는 숫자에 b진법의 거듭제곱을 곱해야 한다.

4. 지수는 string의 길이에서 1을 뺀 값이 최대 지수이다.

5. 반복문을 순회하면서, i값을 감소시키며 지수를 계산해 주자

6. int 배열에 들어있던 원소들과 맞는 거듭제곱값을 곱해 total에 더해준다

#include <algorithm>
#include <iostream>
#include <math.h>

using namespace std;

int main() {

  int b = 0;
  string n;
  int arr[100] = {0,};
  int total = 0;
  double power = 0.0;

  cin >> n >> b;

  for(int i=0; i<n.length(); i++){
    
    if(n[i]>47 && n[i]<58){arr[i] = n[i]-48;}
    else if(n[i]>64 && n[i]<91){arr[i] = n[i]-55;}
  }
  for(int i=n.length()-1; i>=0; i--){
    power = pow(b, n.length()-1-i);
    total += arr[i]*power;
  }
  cout << total;
  return 0;
}