C++字符串拼接异常:Count and Say问题输出不符预期
Count and Say问题的错误原因分析
你的代码在处理ans += to_string(say[i]);时出现核心问题,导致输出结果完全不符合预期。
问题代码
#include <bits/stdc++.h> using namespace std; class Solution { public: string countAndSay(int n) { string ans = ""; if (n == 1) { return "1"; } string say = countAndSay(n - 1); int j = 0, i = 0; while (i < say.size()) { while (say[j] == say[i] && j < say.size()) { j++; } int diff = j - i; ans += to_string(diff); ans += to_string(say[i]); // 错误所在 i = j; } return ans; } }; int main() { Solution sol; cout << sol.countAndSay(4) << "\n"; return 0; }
错误原因
say[i]是char类型,比如字符'1'对应的ASCII码值是49。C++的to_string函数没有专门处理char的重载,传入char时会被隐式转换为int类型,也就是取字符对应的ASCII数值。因此to_string('1')生成的是字符串"49",而非你期望的"1",这直接导致最终拼接出完全错误的结果。
修正方案
有两种简单的修正方式:
- 直接拼接
char类型字符:ans += say[i];,std::string的+=运算符支持直接添加单个字符。 - 把字符转换为单字符字符串:
ans += string(1, say[i]);,通过string构造函数生成仅包含目标字符的字符串。
修正后的代码示例
#include <bits/stdc++.h> using namespace std; class Solution { public: string countAndSay(int n) { string ans = ""; if (n == 1) { return "1"; } string say = countAndSay(n - 1); int j = 0, i = 0; while (i < say.size()) { while (say[j] == say[i] && j < say.size()) { j++; } int diff = j - i; ans += to_string(diff); ans += say[i]; // 直接拼接字符 i = j; } return ans; } }; int main() { Solution sol; cout << sol.countAndSay(4) << "\n"; // 输出:1211 return 0; }
内容的提问来源于stack exchange,提问作者Mantis
相关产品推荐
相关产品推荐

