정신과 시간의 방
카테고리
작성일
2024. 8. 3. 19:36
작성자
risehyun
  • 문제

 

  • 풀이

1. string을 int로 변환해주는 stoi를 이용해서 바로 답을 출력하는 방법

#include <iostream>
#include <string>
using namespace std;

int main()
{
	string N;
	int B;
	cin >> N >> B;

	cout << stoi(N,0,B) << endl;
	return 0;
}

 

이 때 stoi 함수는 다음과 같이 구성된다.

int stoi(const string& str, size_t* idx = 0, int base = 10);
long stol(const string& str, size_t* idx = 0, int base = 10);
float stof(const string& str, size_t* idx = 0)
double stod(const string& str, size_t* idx = 0)

 

 

2. 정석적으로 진법 변환 공식을 사용해서 답을 출력하는 방법

#include<iostream>
#include<algorithm>
#include<math.h>
#include<string>
using namespace std;

int main() 
{
	string N; // B진법 수 N
	int B; // B진법

	cin >> N >> B;

	int result = 0;
	int length = N.length();

	for (int i = 0; i < length; i++)
	{
		// 입력받은 문자열의 뒷부분부터 하나씩 빼서 사용한다.
		int temp = N[length - (i + 1)];

		// 숫자라면 해당 문자에서 '0'을 빼서 실제 숫자로 만듦
		if ('0' <= temp && temp <= '9')
		{
			temp = temp - '0';
		}
		// 알파벳 대문자라면 해당 문자에서 + 10 - 'A'를 해서 실제 문자로 만듦
		else 
		{
			temp = temp + 10 - 'A';
		}

		result += (temp * (int)pow(B, i));
	}

	cout << result << '\n';

	return 0;
}