I was solving a problem on leetcode: Count and say, and wrote the following program:
#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;
}
while i was expecting "1211", it was giving "149152157149153150149153155" as an answer.
I tried to debug this and found that ans += to_string(say[i]);
this was concatenating unexpected value.
eg:- say="1", i=0, j=1, diff = 1 and ans="" after ans += to_string(diff);
has already concatenated "1",
instead of concatenating "1" to_string(say[i]);
is concatenating "49".
Can anyone please explain what is happening?