I was working on a question that requires a concatenation of strings recursively and ran into a problem.
Question states that s(0) = 0, s(1) = 1, s(n) = s(n-1)s(n-2) for n >= 2
, where s(n)
is the concatenated string of the previous two strings.
Input will indicate how many instances of (n, k)
pair will be input as the first integer, followed by each line containing a non-negative integer
n (0 <= n <= 60)
and a positive integer k
.
Output is supposed to be printing out the kth character of the concatenated string s(n)
, where k
is less or equal to the number of characters in string s(n)
.
s(0) = 0
s(1) = 1
s(2) = 10
s(3) = 101
s(4) = 10110
s(5) = 10110101
and so on.
Sample input:
3
5 2
0 1
4 3
Output:
0
0
1
My code:
import java.util.*;
public class recursivestring {
public static String recursive(int n, int i, String str1, String str2){
if (i == n - 1)
return str1 + str2;
return recursive(n, i + 1 , str1 + str2, str1);
}
public static void main(String[] args) {
int lines, i, n, k;
String result;
Scanner input = new Scanner(System.in);
lines = input.nextInt();
for (i = 0; i < lines; i++) {
n = input.nextInt();
k = input.nextInt();
if (n == 0) {
result = "0";
} else if (n == 1) {
result = "1";
} else if (n == 2) {
result = "10";
} else {
result = recursive(n, 2, "10", "1");
}
System.out.println(result.charAt(k-1));
}
}
}
This is what I have so far, and it works for the given sample test case. It works for most cases but once n becomes large, I get this error
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
Why is that happening and is there something wrong with my code?
Thank you!