【洛谷】P1143 进制转换

题目地址:

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

#include 
#include 
#include 

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;
}

你可能感兴趣的:(洛谷题解配证明)