repeated-string
https://www.hackerrank.com/challenges/repeated-string/forum
function repeatedString($s, $n) { // Length of the original string $s_len = strlen($s); // Count 'a' occurrences in the original string $a_in_s = 0; for ($i = 0; $i < $s_len; $i++) { if ($s[$i] == 'a') { $a_in_s++; } } // Calculate full string repetitions $whole_repetitions = floor($n / $s_len); // Count 'a' in full repetitions $total_a = $a_in_s * $whole_repetitions; // Handle the remainder $remainder = $n % $s_len; // Count 'a' in the remainder for ($i = 0; $i < $remainder; $i++) { if ($s[$i] == 'a') { $total_a++; } } return $total_a; } // Read input (replace with actual input mechanism) $s = fgets(STDIN); $n = (int)fgets(STDIN); // Call the function and print the result $result = repeatedString(trim($s), $n); echo $result;
Comments
Post a Comment