輸入十進制整數 a 與目標基數 R (2≤R≤9),輸出 a 的 R 進制表示。經典棧應用——「除基取餘,逆序輸出」。
a > 0:push(a % R),a /= R!stack.empty():pop() 輸出
| 版本 | 核心代碼 | 優缺點 |
|---|---|---|
| STL stack | stack | 代碼簡潔,生產級可用 |
| 手寫數組棧 | int top=-1; s[++top]=val; | 教學演示底層機制,無依賴 |
| 庫函數 itoa | itoa(a, buf, r); | 非標準,Windows 專用,不可移植 |
#include <cstdio>
#include <stack>
using namespace std;
int main() {
long long a; int r;
while (scanf("%lld %d", &a, &r) == 2) {
stack S;
if (a == 0) { putchar('0'); putchar('\n'); continue; }
while (a > 0) {
S.push(a % r);
a /= r;
}
while (!S.empty()) {
printf("%d", S.top());
S.pop();
}
putchar('\n');
}
return 0;
}
long long 或大整數庫