fix: numbersofAs

This commit is contained in:
Sami 2024-11-12 12:36:29 -05:00
parent ba2db6a59e
commit f8748fcbdf
2 changed files with 117 additions and 0 deletions

Binary file not shown.

View File

@ -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;
}
}