백준 - 2745번 진법 변환(문자열, stoi)

Kiwoong Park·2023년 5월 27일
0

문제

B진법 수 N이 주어질 때 10진법으로 바꿔 출력하기

C++ 풀이

문자열로 받아 아스키 코드인 숫자로 변환 후 진법대로 계산하는 방식으로 접근하였다.
10진법 이상일 경우 영문이 나오기 때문에 삼항연산자로 따로 지정해줬다.

#include <bits/stdc++.h>
using namespace std;

int main()
{
int N,n,tot=0,len;
string B;
cin >> B >> N;
len=B.length()-1;
for (int b:B) {
n=((N>10 && b>='A')?b-'A'+10:n=b-'0');
tot+=n*pow(N,len--);
}
cout<<tot;
}


### 숏코딩 분석하기
> 숏코딩을 보니 간단히 stoi 내장 함수를 써서 문자열을 n진법의 정수형으로 파싱해서 정수값으로 출력한다. 
stoi() : Parses str interpreting its content as an integral number of the specified base, which is returned as an int value.
```c
#include <bits/stdc++.h>
using namespace std;
int main(){
	string s;
	int n;
	cin >>s >>n;
	cout<<stoi(s,0,n);
	return 0;
}
profile
You matter, never give up

0개의 댓글