- 문제
- 풀이
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;
}
'코딩테스트' 카테고리의 다른 글
[백준/5086번/C++] 배수와 약수 (0) | 2024.08.06 |
---|---|
☆ [백준/2903번/C++] 중앙 이동 알고리즘 (0) | 2024.08.04 |
[백준/2720번/C++] 세탁소 사장 동혁 (0) | 2024.08.02 |
☆ [백준/1193번/C++] 분수찾기 (0) | 2024.08.01 |
☆ [백준/11005번/C++] 진법 변환 2 (0) | 2024.07.31 |