算法題----任意進制轉換(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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM