2

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?

Mantis
  • 23
  • 5
  • `j < say.size()` is checked at too late time, after the wrong access `say[j]` happens, that leads to the undefined behavior world. – 273K Oct 19 '22 at 05:04
  • It would be nice if you added the few missing lines, the includes and `using namespace...`, to make the code a proper [mcve]. – hyde Oct 19 '22 at 05:09
  • [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Jesper Juhl Oct 19 '22 at 09:42

1 Answers1

3
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.

hyde
  • 60,639
  • 21
  • 115
  • 176
  • Oh, so `say[i]` was returning an int and `to_string()` was converting that int value to String, as 49 is ascii value of "1" it was concatenating "49". Thank you so much! – Mantis Oct 19 '22 at 05:12
  • 1
    @Mantis No, `say[i]` returns a char. But there is no `std::to_string(char)`. – hyde Oct 19 '22 at 05:15
  • 1
    @Mantis So yes, here `to_string` returns the ASCII value as string, after conversion to int. – hyde Oct 19 '22 at 05:18