计数本的java代码_Java:保存递归本地计数器的值

如何保存并返回计数器的最终值?

也许您应该将其改为“如何保存计数器的返回值?”,答案是:

使用返回值。

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

是匹配的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值