0

I attempted the following: The count-and-say sequence is the sequence of integers beginning as follows:

1, 11, 21, 1211, 111221, ... 1 is read off as one 1 or 11. 11 is read off as two 1s or 21.

21 is read off as one 2, then one 1 or 1211.

Given an integer n, generate the nth sequence.

I actually wrote some code to solve this problem and it was not generating the right answer.The problem in the code is that i tried to add a character to a string using the "+" operator.

string Solution::countAndSay(int A) { string s = "11"; string str; string ans[A + 2]; ans[1] = "1"; ans[2] = "11"; int count = 1; for (int j = 3; j <= A; j++) { str = ""; count = 1; for (int i = 0; i < s.size() - 1; i++) { if (s[i] == s[i + 1]) count++; else { str += to_string(count) + s[i]; count = 1; } } if (s[s.size() - 1] != s[s.size() - 2]) { str += "1" + s[s.size() - 1]; } else str += to_string(count) + s[s.size() - 1]; ans[j] = str; s = str; } return ans[A]; } 

When i changed the code inside the if condition below in the nested loop it worked. The change i did was:

if(s[s.size()-1]!=s[s.size()-2]){ str+="1"; str.push_back(s[s.size() - 1)]; } 

I just want to know what was wrong in earlier code. Can we not use a "+" operator to add characters to a string?

2

1 Answer 1

1
str += "1" + s[s.size() - 1]; 

Does not mean

str += "1"; str += s[s.size() - 1]; 

But

str += ("1" + s[s.size() - 1]); 

where the right-hand-side expression is not at all what you wanted.

  1. The expression "1" is not a char, but a string literal containing the two characters {'1', 0} (it's a C string, so there is a null terminator).

  2. Then, "1" + ... isn't an append like your top-level operation, because C strings don't have overloaded operators, but just decay to a pointer.

  3. Now you're doing pointer arithmetic, so s[s.size() - 1] is promoted from a char to an integer, and added to the address of the first character in your string literal.

    Unless the character was 0 or 1 (and I don't mean '0' or '1'), the result is off the end of your string literal, and behaviour will be undefined.

  4. str += (...) is now appending a C-string, which it is illegal to even look at (due to the UB above).

The reason that

str += to_string(count) + s[i]; 

works, is that the left-hand side of to_string(count) + s[i] is a std::string with an overloaded operator+. You can get the same effect by writing

str += string{"1"} + s[s.size() - 1]; 

so you also have a std::string instead of a C string literal as the left-hand side of the operator+.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.