diff --git a/InfinitString/InfinityString.class b/InfinitString/InfinityString.class new file mode 100644 index 0000000..9072325 Binary files /dev/null and b/InfinitString/InfinityString.class differ diff --git a/InfinitString/InfinityString.java b/InfinitString/InfinityString.java new file mode 100644 index 0000000..3f0e402 --- /dev/null +++ b/InfinitString/InfinityString.java @@ -0,0 +1,117 @@ +import java.util.Scanner; + +/** + * InfinityString + * There is a string, , of lowercase English letters that is repeated infinitely + * many times. Given an integer, , find and print the number of letter a's in + * the first + * + * letters of the infinite string. + * + * Example + * + * The substring we consider is , the first characters of the infinite string. + * There are + * + * occurrences of a in the substring. + * + * Function Description + * + * Complete the repeatedString function in the editor below. + * + * repeatedString has the following parameter(s): + * + * s: a string to repeat + * n: the number of characters to consider + * + * Returns + * + * int: the frequency of a in the substring + * + * Input Format + * + * The first line contains a single string, + * . + * The second line contains an integer, + * + * . + * + * Constraints + * + * For of the test cases, + * + * . + * + * Sample Input + * + * Sample Input 0 + * + * aba + * 10 + * + * Sample Output 0 + * + * 7 + * + */ +public class InfinityString { + + public static void main(String[] args) { + + // MY SOLUTION IS SLOW BUT IT WORKS + Scanner sc = new Scanner(System.in); + System.out.println("Please enter your 'String' here and it must contains the letter A: "); + String str = sc.nextLine(); + System.out.println("Please enter how many times you want to repeat that: "); + int x = sc.nextInt(); + System.out.println(numsOfAs(str, x)); + sc.close(); + } + + // + // private static int numsOfAs(String str, int n) { + // int numberOfAs = 0; + // int x = n; + // String newSTR = ""; + // int remeinder = n / str.length(); + // while (n > 0 && newSTR.toCharArray().length < n + remeinder) { + // newSTR += str; + // n--; + // } + // + // char[] charNewstr = newSTR.toCharArray(); + // for (int i = 0; i < x; i++) { + // if (charNewstr[i] == 'a') { + // numberOfAs++; + // } + // } + // return numberOfAs; + // + // + private static int numsOfAs(String str, int n) { + int numberOfAs = 0; + int numRepeats = n / str.length(); + int remainder = n % str.length(); + + // Count the number of 'a' characters in the repeated string + numberOfAs = countAs(str) * numRepeats; + + // Count the number of 'a' characters in the remaining portion + if (remainder > 0) { + numberOfAs += countAs(str.substring(0, remainder)); + } + + return numberOfAs; + } + + private static int countAs(String str) { + int count = 0; + for (char c : str.toCharArray()) { + if (c == 'a') { + count++; + } + } + return count; + } + +}