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?
CodePudding user response:
ans = to_string(say[i]);
That line ends up converting say[i]
as an integer (because char
is an integer type!).
Solution, add it as a character:
ans = say[i];
For your convenience:
https://en.cppreference.com/w/cpp/string/basic_string/to_string
And the lesson here is: if a line with a library function call does funny thing things, read the docs of the function.