算法题----任意进制转换(C++)

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

int toInt(char c)
{
//    char c = s;
    if(c >= '0' && c<= '9') return c - '0';
    else if(c >= 'a' && c<= 'z') return c - 'a' + 10;
    else return c - 'A' + 10;
}

int main()
{
    int a, b; // a原进制,b转换进制
    cin >> a>> b;
    string str; // 用字符串表示的数字
    cin >> str;

    bool negative = false;  // 标记是否为负数,false为正,true为负

    if(!str.empty())    // 去掉数字前的所有空格
    {
        str.erase(0,str.find_first_not_of(" "));
    }

    if(str[0] == '+')
        str = str.substr(1,str.length() - 1);
    else if(str[0] == '-')
    {
        negative = true;
        str = str.substr(1,str.length() - 1);
    }

    int y = 0; // str的十进制表示
    int aa = 1; // 表示每次计算中进制的幂次
    for(int i = str.length() - 1; i >= 0; i--)
    {
        y = y + toInt(str[i]) * aa;
        aa = aa * a;
    }
    string res;
    string tmp;
    do{                       // 此处一定要用do...while(),防止输入是0的情况
        tmp = to_string(y%b) ;
        y = y / b;
        res  = tmp + res;
    }while (y!=0);

    if(negative)
        res = '-' + res;
    cout << res << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/myblog1993/p/11458189.html