The exercise is to write a recursive method that takes a String and a char parameter and returns a String with each occurrence of the char doubled. Additionally, the number of doubling operations should be added at the end of the string. No "extern" variables outside the method are allowed to use. The String parameter can contain any valid char, including numbers.
My code works up to 1000 doubling operations, but not correctly for 1001. My question is whether this is just a rounding error or whether this task is theoretical unsolvable.
public class Doubly {
public static String doubly(final String s, final char c) {
if (s.length() > 0) {
if (c == s.charAt(0)) {
int len1 = s.length();
String s1 = "" + c + c + doubly(s.substring(1), c);
int len2 = s1.length();
int lenDiff = len2 - len1;
int log = (int) Math.log10(lenDiff - Math.log(lenDiff + 1) + 1) + 1;
if (log > 0) {
int n = Integer.parseInt(s1.substring(s1.length() - log));
return s1.substring(0, s1.length() - log) + (n + 1);
}
return s1;
}
return "" + s.charAt(0) + doubly(s.substring(1), c);
}
return "0";
}
public static void main(final String[] args) {
String s = "ccc";
for (int i = 0; i < 1500; i++) {
s += "a";
String s2 = doubly(s, 'a');
System.out.println("Expected: " + (i + 1) + ", actual: " + s2.substring(s2.length() - (int) Math.log10(i + 1) - 1));
if (!String.valueOf(i + 1)
.equals(s2.substring(s2.length() - (int) Math.log10(i + 1) - 1))) {
System.out.println("ERROR");
return;
}
}
}
}