题解 | #进制转换#栈思虑

进制转换

https://www.nowcoder.com/practice/ac61207721a34b74b06597fe6eb67c52

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

int main()
{
    int M, N;
    cin >> M >> N;
    int flag = 0;
    if (M < 0)
    {
        M = -M;
        flag = -1;
    }

    if (M == 0)
    {
        cout << "0" << endl;
        return 0;
    }

    string str = "", str2 = "";
    stack<int> s;
    while (M)
    {
        int t = M % N;
        s.push(t);
        M /= N;
    }

    string tmp = "0123456789ABCDEF";
    while (!s.empty())
    {
        int t = s.top();
        str += tmp[t];
        s.pop();
    }

    if (flag)
    {
        str = "-" + str;
    }

    cout << str << endl;

    return 0;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务