酷代码 AI
菜单
服务商

C++统计整数中0、1、2出现次数的方法与实现

好的,我们一起来解决这个问题。这是一个非常基础的**数字统计**问题,主要考察对字符串或数字逐位处理的能力。 --- ## 📘 问题分析 我们需要统计一个整数 `n` 中数字 **0、1、2** 分别出现的次数。 **核心思路**: 1. 将整数 `n` 当作字符串处理(或者逐位取模)。 2. 遍历每一位数字,分别统计 `0`、`1`、`2` 的个数。 3. 最后以空格分隔输出三个统计结果。 --- ## 🧩 解法:C++ 实现 ### 🔧 方法一:字符串遍历法(推荐,简洁易懂) ```cpp #include <iostream> #include <string> using namespace std; int main() { string n; cin >> n; // 直接输入字符串 int count0 = 0, count1 = 0, count2 = 0; for (char ch : n) { if (ch == '0') count0++; else if (ch == '1') count1++; else if (ch == '2') count2++; } cout << count0 << " " << count1 << " " << count2 << endl; return 0; } ``` ### 🛠 方法二:整数取模法(纯数字处理) ```cpp #include <iostream> using namespace std; int main() { long long n; // 注意:如果数字很大,要用 long long cin >> n; if (n == 0) { // 如果 n 本身就是 0,那么只有一位数字 0 cout << "1 0 0" << endl; return 0; } int count0 = 0, count1 = 0, count2 = 0; while (n > 0) { int digit = n % 10; // 取最低位 if (digit == 0) count0++; else if (digit == 1) count1++; else if (digit == 2) count2++; n /= 10; // 去掉最低位 } cout << count0 << " " << count1 << " " << count2 << endl; return 0; } ``` --- ## ✅ 测试样例 ### 输入样例1: ``` 20200115 ``` ### 输出结果: ``` 3 2 2 ``` ### 输入样例2: ``` 902 ``` ### 输出结果: ``` 1 0 1 ``` --- ## ⚠️ 常见陷阱与注意事项 | 陷阱 | 说明与建议 | |------|------------| | **数字前导零问题** | 输入是整数,不会出现前导零,如 `001` 会被当作 `1`,所以用整数法时不需要处理前导零。 | | **大数溢出** | 如果 `n` 可能超过 `int` 范围,建议用 `long long` 或直接读入字符串。 | | **n 为 0 的情况** | 整数法需要特殊处理,因为 `while(n > 0)` 会直接跳过。字符串法则自然处理。 | --- ## 💡 开发建议 1. **优先使用字符串读入法**:更安全,避免数字溢出,且代码更短。 2. **注意代码的可扩展性**:如果以后要统计更多数字(0-9),可以用数组 `count[10]` 来统一处理。 3. **考虑使用范围 for 循环**(C++11以上):让代码更现代、易读。 --- ## 📚 扩展:通用版本(统计 0-9 所有数字) ```cpp #include <iostream> #include <string> using namespace std; int main() { string n; cin >> n; int count[10] = {0}; // 下标0~9分别对应数字0~9 for (char ch : n) { count[ch - '0']++; // 字符转数字 } // 只输出0、1、2的统计结果 cout << count[0] << " " << count[1] << " " << count[2] << endl; return 0; } ``` --- ## 🔗 学习资源推荐 - [C++ 字符串基础 (cppreference)](https://en.cppreference.com/w/cpp/string/basic_string) - [C++ 循环与条件判断](https://en.cppreference.com/w/cpp/language/for) --- 如果还有其他问题或需要进一步优化代码,欢迎继续交流! ######[AI写代码神器 | 1020点数解答 | 2026-05-23 22:09:32]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]