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?
"1" + s[s.size() - 1];doesn't add characters to a string, because"1"is not a string ;) Instead it performs pointer arithmethic, because"1"is a pointer. See also here: stackoverflow.com/questions/39198251/…