返回在num递归中找到的相同数字的最长序列的长度

  • 本文关键字:数字 递归 num 返回 java recursion
  • 更新时间 :
  • 英文 :


我有一个任务;

"编写一个递归静态方法,接受一个正整数num,并返回num中相同数字的最长序列的长度。">

这是我做的解决方案

public static int equalDigits (int num)
{
return equalDigits(num,1,0);
}
private static int equalDigits (int num, int count, int max){ 
if (num < 10)
return 1;
if (num/10%10 == num%10)
count++;
else
count = 1;
max = count > max ? count : max;
return Math.max(max,equalDigits(num/10,count,max));
}

但是我的讲师说不使用helper方法也可以做到。我想不出这到底是怎么可能的。

下面是一些使用你的方法的代码,所以没有使用String(我认为它很丑):

public static int equalDigits(int num)
{
// this is a so-called guard statement at the start to disallow invalid arguments
if (num < 0) {
throw new IllegalArgumentException("Expecting positive value or zero");
}

int currentDigit = -1; // "magic value" outside of range
int count = 0;
int maxCount = 0;
int x = num; // good practice not to operate on parameters
while (x > 0) {
int digit = x % 10;
if (digit == currentDigit) {
count++;
} else {
// only update max count when needed
// TODO set maxcount
// TODO something with digits
// don't forget the initial digit, so not zero
// TODO set initial count
}
x /= 10; // yes, it exists, is identical to x = x / 10
}
// if the last count was higher we still need to adjust
// TODO set maxcount

return maxCount;
}

我已经删除了让它工作所需的东西,但我已经展示了如何在没有递归操作的情况下实现这一点,因为递归操作很难重构。

最新更新