From HackerRank "Repeated String" challenge:
Lilah has a string, \$s\$, of lowercase English letters that she repeated infinitely many times.
Given an integer, \$n\$, find and print the number of letter a's in the first \$n\$ letters of Lilah's infinite string.
For example, if the string \$s=abcac\$ and \$n=10\$, the sub string we consider is \$abcacabcac\$, the first \$10\$ characters of her infinite string. There are \$4\$ occurrences of a in the sub-string.
Test case 1:
string input = "aba";
long n = 10;
Test case 2:
string input = "a";
long n = 1000000000000;
My Solution:
string input = "aba";
long n = 10;
long numAs = input.Count(c => c.Equals('a'));
if (input.Length == 0)
{
return 0;
}
long rem = n % input.Length;
long reps = (n - rem) / input.Length;
long count = reps * numAs;
string sRem = input.Substring(0, (int)rem);
if (rem != 0)
{
count += sRem.Count(c => c.Equals('a'));
}
The results should be 7 and 1000000000000. This solution passed all test cases on HackerRank. It is based on other solutions, especially one I up-voted.
input
missing null validation.n
missing negative integers && 0 validation. \$\endgroup\$