Reputation: 29
I am doing the hacker rank warmups and I have the logic down for repeating strings but am getting an string index out of range and not sure how to fix it. Could someone help with this?
public static long countAs(String s, long n) {
long count;
long length = s.length();
long q = n / length;
long r = n % length;
long partial = 0;
partial = r;
count = q * getLetterCount(s, q) + getLetterCount(s, partial);
return count;
}
public static long getLetterCount(String s, long length) {
long count = 0;
for (int i = 0; i < length; i++) {
if (s.charAt(i) == 'a') {
count++;
}
}
return count;
}
Upvotes: 1
Views: 61
Reputation: 328
for (int i = 0; i < length; i++)
For this line, i is int and length is long, they have different value range! when i = int_max +1 the runtime error will appear
Upvotes: 0
Reputation: 2981
There is only one place in your code where that can happen:
for (int i = 0; i < length; i++) {
if (s.charAt(i) == 'a') { // <- HERE
count++;
}
}
When you are calling s.chartAt(i)
most likely i
is bigger than the size of the string s
. Please check the value of long length
you are passing to getLetterCount()
.
Upvotes: 2