我在 leetcode 上解决了一个问题:Count and say,并编写了以下程序:
#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;
}
当我期待“1211”时,它给出了“149152157149153150149153155”作为答案。
我尝试对此进行调试,发现 ans += to_string(say[i]);
这是连接意外值。
例如:- 在 ans += to_string(diff);
之后说="1", i=0, j=1, diff = 1 和 ans=""已经连接了“1”,
to_string(say[i]);
不是连接“1”,而是连接“49”。
谁能解释一下发生了什么?
最佳答案
ans += to_string(say[i]);
该行最终将 say[i]
转换为整数(因为 char
是整数类型!)。
解决方案,将其添加为字符:
ans += say[i];
为了您的方便:
https://en.cppreference.com/w/cpp/string/basic_string/to_string
这里的教训是:如果带有库函数调用的行做了有趣的事情,阅读该函数的文档。
关于c++ - 字符串连接 C++ 给出意想不到的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74120075/