1 条题解
-
0
【例35.1】 分离整数的各个数位
解题思路
反复用 n%10 取当前个位并输出,再 n/=10 删除该位,直到全部取完。
正确性说明
按上述推导执行:每次仅处理当前输入或当前步骤,并把它对答案的贡献计入对应状态。所有需要处理的情况均被覆盖,结束时保存的量就是题目所求。
易错点
各位之间空格;个位0也需输出。
复杂度
数字D位,时间O(D),空间O(1)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); long long n; cin >> n; bool first = true; do { if (!first) cout << " "; cout << n % 10; first = false; n /= 10; } while (n); cout << "\n"; return 0; }
- 1