Difficulty: Easy
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.
Note: The sequence of integers will be represented as a string.
Subscribe to see which companies asked this question
Hide Tags
Show Similar Problems
-------------------------------------
-------------------------------------
Change this problem to: for any input not 1, like
string countAndSay(int n, int b) {
where b is the any input and n means output n repetitions. For example, when b=111123, the procedure
will be like following:
The whole project for above problem
////////////////////////////////////////////////////////
//project
#include "stdafx.h"
#
include <cstdlib>
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
#
include <map> // std::map
#
include <unordered_map>
#
include <string>
#include <bitset>
#include <ctype.h>
#include <sstream>
using namespace std;
class Solution {
public:
string countAndSay(int n, int b) {
string final;
//check
input
//if(n==NULL)retun
final;
final += to_string(b);
final += ",
";
string tmp = to_string(b), tmpStore;
char digi = tmp[0];
for (int i = 0; i<n; i++){
int count = 0,j=0;
//
for (; j<tmp.size(); j++){
if (tmp[j] != digi || j==tmp.size()){
final += to_string(count);
final += tmp[j-1];
//store
current string
tmpStore += to_string(count);
tmpStore += tmp[j-1];
//adjust
the parameters
count = 0;
digi = tmp[j];
j--;
}
else{
count++;
}
}
//put on
the lefts
final += to_string(count);
final += tmp[j-1];
tmpStore += to_string(count);
tmpStore += tmp[j-1];
final += ",
";
//adjust
the parameters
tmp = tmpStore;
tmpStore.clear();
digi = tmp[0];
cout << final << endl;
}
//remove
last ", "
final.erase(final.end() - 2, final.end());
return final;
}
};
int main(int argc, char *argv[])
{
Solution s;
string outt = s.countAndSay(10,22);
}
No comments:
Post a Comment