C++ Solution: Repeated String Hackerrank

Repeated String 


Code

#include<bits/stdc++.h>

#include<string>

using namespace std;


int main()

{

    long long int n,i,x,y,c=0;

    string s;

    cin>>s;                                  // input string

    cin>>n;                             // input size or number of character


    for(i=0;i<s.size();i++)                     // counting the  number of a’s

    {

        if(s[i]=='a')

        {

            c++;

        }

    }

    y=n/s.size(); // calculating how many cycles to perform

    c=y*c; // for each cycle the no of a’s will be same as same string is repeated hence y cycle contains c*y number of a’s

    

for(i=0;i<n%s.size();i++) // there may be few elements of string which are repeated at last to complete the size required 

    {

        if(s[i]=='a’) // this loop will count the no of a’s in that remaining string

        {

            c++;

        }

    }

    cout<<c;

    

    return 0;

}


Repeated String Hackerrank Solution in C++

You can post your own solutions in any language in comments section we will review and post with your credits. 

Post a Comment

0 Comments