I've created a method that counts the number of all matching digits from two given integers. Everything in the method seems to work as it should except the local counter.
The counter does "work" at counting the number of matching digits all the way to the final recursive iteration. However, as the recursion works it's way back out, the final (and desired) value is lost as all the previous values are cycled through until it reaches the original value. This means that no matter what value the counter got to during all the iterations, it will still always return 0.
How can I save and return the final value of the counter? Any help would be much appreciated, thanks.
public static int match(int a, int b) {
return matchHelper(a, b, 0);
}
private static int matchHelper(int a, int b, int c) {
int count = c;
String strA = Integer.toString(a);
String strB = Integer.toString(b);
if (a < 0 || b < 0) {
throw new IllegalArgumentException();
} else {
// Check and count
if (strA.charAt(strA.length() - 1) == strB.charAt(strB.length() - 1)) {
count++;
}
// Remove last char and call again
if (strA.length() > 1 && strB.length() > 1) {
strA = strA.substring(0, strA.length() - 1);
strB = strB.substring(0, strB.length() - 1);
matchHelper(Integer.parseInt(strA), Integer.parseInt(strB), count);
}
}
return count;
}
NOTE: This method has many requirements and restrictions that has caused it to be coded this way (no loops, no structured objects, must be recursion, ect..). I'm sure there is a better way of doing this. However, my primary concern pertains to returning the correct value of the counter. Thanks.