안녕하세요. 오늘은 8진수, 10진수, 16진수를 만들어볼 거예요.

문제

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

아이디어

문자열로 입력받고 세가지로 나누면 됩니다.
1. 맨 앞 두글자가 0x인 경우
2. 맨 앞 글자가 0인 경우
3. 둘다 아닌경우
각각 16진수, 8진수, 10진수로 바꿔서 출력해주면 됩니다.

소스코드

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

int char_int(char c)
{
    if ('0' <= c && c <= '9') return c - '0'; //숫자
    else return c - 'a' + 10; //영어 소문자
}

int to_int(string s, int x) //바꿀 문자열, x진수를
{
    int ans = 0, len = s.length(), i, mul = 1;
    for (i = len - 1; i >= 0; i--)
    {
        ans += char_int(s[i]) * mul;
        mul *= x;
    }
    return ans;
}

int main(void)
{
    ios_base::sync_with_stdio(false); cin.tie(NULL);
    string s;
    cin >> s;
    if (s.length() >= 2 && s[0] == '0' && s[1] == 'x') cout << to_int(s.substr(2, s.length() - 2), 16);
    else if (s.length() >= 1 && s[0] == '0') cout << to_int(s.substr(1, s.length() - 1), 8);
    else cout << s;
}


감사합니다.

0개의 댓글