如何保存并返回计数器的最终值?
也许您应该将其改为“如何保存计数器的返回值?”,答案是:
使用返回值。
count = matchHelper(...);
你其实不需要
c
+=
取而代之的是:
public static int match(int a, int b) {
int count = 0;
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);
count += match(Integer.parseInt(strA), Integer.parseInt(strB));
}
}
return count;
}
你的代码真的走得很慢,把数字转换成字符串只是为了提取最后一个数字。不要那样做,用除法和余数。
public static int match(int a, int b) {
if (a < 0 || b < 0)
throw new IllegalArgumentException();
int count = 0;
if (a % 10 == b % 10) // compare last digit
count++;
if (a >= 10 && b >= 10)
count += match(a / 10, b / 10); // recurse with last digit removed
return count;
}
如果您坚持使用字符串,只需在开始时转换为字符串一次,然后向后“迭代”比较数字。
public static int match(int a, int b) {
if (a < 0 || b < 0)
throw new IllegalArgumentException();
String strA = Integer.toString(a);
String strB = Integer.toString(b);
return matchHelper(strA, strB, strA.length() - 1, strB.length() - 1);
}
private static int matchHelper(String strA, String strB, int aIdx, int bIdx) {
int count = 0;
if (strA.charAt(aIdx) == strB.charAt(bIdx))
count++;
if (aIdx > 0 && bIdx > 0)
count += matchHelper(strA, strB, aIdx - 1, bIdx - 1);
return count;
}
此答案中显示的所有4种解决方案产生相同的结果(
3
match(1236456789, 51782)
,自数字
5
,
7
,和
8
是匹配的。