我在解決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]);這是連接意外值。例如:- say="1", i=0, j=1, diff = 1 and ans="" afterans = to_string(diff);已經連接了“1”,而不是連接“1”to_string(say[i]);是連接“49”。誰能解釋發生了什么?
uj5u.com熱心網友回復:
ans = to_string(say[i]);
該行最終轉換say[i]為整數(因為char是整數型別!)。
解決方案,將其添加為字符:
ans = say[i];
為了您的方便:
https://en.cppreference.com/w/cpp/string/basic_string/to_string
這里的教訓是:如果帶有庫函式呼叫的行做了有趣的事情,請閱讀函式的檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/517888.html
標籤:C 数组细绳级联
上一篇:事件回圈Event Loop
