close nav

close nav

Thread: Regarding for nth term in Count and Say sequence.

Forum : Basic C   11 Feb, 2021
User Image
ankitdixit

Newbie

Joined: 11 Feb, 2021

Points: 100

Threads: 1

Posts: 0

Regarding for nth term in Count and Say sequence.

| Quote Date : 11 Feb, 2021    Views:246    

Hello Everyone, I am 1 year experience in C++ and I have faced a interview in Facebook. Interviwer asked me, Can you explain how to find the nth term in Count and Say sequence. I am sharing a code syntax below with i found by this post. Can anyone suggest me, Is it right?

#include <bits/stdc++.h>
using namespace std;
string countnndSay(int n)
{
if (n == 1) return "1";
if (n == 2) return "11";
string str = "11";
for (int i = 3; i<=n; i++)
{
str += '$';
int len = str.length();
int cnt = 1;
string tmp = "";
for (int j = 1; j < len; j++)
{
if (str[j] != str[j-1])
{
tmp += cnt + '0';
tmp += str[j-1];
cnt = 1;
}
else cnt++;
}
str = tmp;
}
return str;
}
int main()
{
int N = 4;
cout << countnndSay(N) << endl;
return 0;
}

tags: c
Load More

No More Comments