【洛谷】P1143 进制转换

题目地址:

https://www.luogu.com.cn/problem/P1143
进制转换。使用栈。

#include <iostream>
#include <string>
#include <stack>

using namespace std;


int main() {
    int n;
    string s;
    int m;

    long long sum = 0;
    cin >> n >> s >> m;
    for (int i = 0; i < s.length(); ++i) {
        sum *= n;
        if (isdigit(s[i])) {
            sum += s[i] - '0';
        } else {
            sum += s[i] - 'A' + 10;
        }
    }
    stack<int> stack;

    while (sum) {
        stack.push(sum % m);
        sum /= m;
    }

    if (stack.empty()) {
        cout << 0 << endl;
    }

    while (!stack.empty()) {
        if (stack.top() < 10) {
            cout << stack.top();
        } else {
            cout << char('A' + stack.top() - 10);
        }
        stack.pop();
    }
    cout << endl;

    return 0;
}
发布了86 篇原创文章 · 获赞 0 · 访问量 1217

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/103998507
今日推荐