輸入正整數,輸出其數字反轉後去除前導零的結果。如 321 → 123,1568 → 8651,1200 → 21。
#include <iostream>
using namespace std;
void reversePrint(int x) {
if (x == 0) return;
cout << x % 10; // 輸出最低位
reversePrint(x / 10); // 遞歸處理高位
}
int main() {
int n;
cin >> n;
reversePrint(n);
cout << endl;
return 0;
}
上述代碼輸入 1200 會輸出 0021。若需去除前導零(即原數尾部零),可先去除尾部零再遞歸:
while (n % 10 == 0 && n != 0) n /= 10;
reversePrint(n);
#include <iostream> using namespace std; void foo(int x) { if (x == 0) return; cout << x % 10; foo(x / 10); } int main() { int i = 123; foo(i); }