1 条题解
-
0
【例34.3】 统计数字字符个数
解题思路
使用 getline 读完整一行,逐字符检查是否在 '0'~'9' 之间,满足就计数。
正确性说明
按上述推导执行:每次仅处理当前输入或当前步骤,并把它对答案的贡献计入对应状态。所有需要处理的情况均被覆盖,结束时保存的量就是题目所求。
易错点
句子可能有空格,不能只用 cin>>s 读一个词。
复杂度
行长 L,时间 O(L),空间 O(L)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string s; getline(cin, s); int ans = 0; for (char c : s) if (c >= '0' && c <= '9') ans++; cout << ans << "\n"; return 0; }
- 1