面试之进制转换函数

进制转换

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

string Convert(int num, int R)
{
    string res;
    vector<int> temp;
    int remainder = 0;
    while (num != 0)
    {
        remainder = num % R;
        num = num / R;
        temp.push_back(remainder);
    }

    vector<int>::reverse_iterator iter;
    for (iter = temp.rbegin(); iter != temp.rend(); iter++)
    {
        if (*iter >= 10)
        {
            res.push_back((char)(*iter - 10) + 'A');
        }
        else
        {
            res.push_back(*iter + '0');
        }
        return res;
    }
}

int main(int argc, char const *argv[])
{
    int num, R;
    string res;
    cout << "输入要转换的数字:" << endl;
    cin >> num;
    cout << "输入要转换的进制:" << endl;
    
    cin >> R;
    res = Convert(num, R);
    cout << "输出的" << R << "进制结果为:" << endl;
    cout << res << endl;
    return 0;
}

posted @ 2020-08-21 19:32  Chilk  阅读(122)  评论(0编辑  收藏  举报