We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
// To count a's in string s
int aCount = 0;
// To count a's in infinite string
long Totalcount = 0;
// Counting a's in string s
for (int i=0; i<s.length(); i++) {
char letter = s.charAt(i);
if (letter == 'a') { aCount++; }
}
// Counting a's in infinite string
// Check whether n is a multiple of s.length()
if (n % s.length() == 0) {
Totalcount = (n / s.length()) * aCount;
}
else {
// Calculate the nearest multiple of s.length() to n
long nearestMultiple = n - (n%s.length());
// Add a's count up to nearest multiple
Totalcount = (nearestMultiple / s.length()) * aCount;
// Add the remaining a's count in the remaining string
for (int i=0; i<n%s.length(); i++) {
char letter = s.charAt(i);
if (letter == 'a') { Totalcount++; }
}
}
return Totalcount;
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Repeated String
You are viewing a single comment's thread. Return to all comments →
Here is my Java 7 solution: