0

提示要求我在下面拥有公共静态并且只使用递归。这是我使用 Java 的第一周,所以我的知识基础非常低。我在网上看到了一些 Luhn 算法的代码,但似乎都没有使用布尔值作为第二个参数。

基本上我需要创建一个 Luhn 算法,它取每个值(从右到左),将第二个值加倍(布尔值用于确定数字是否会加倍),然后将所有值加在一起。例如)。System.out.println(sumLuhnDigits(7992739871005L, false));

将返回 72

我遇到的问题是“长”类型。

Java 告诉我我需要在将 count 变量设置为等于 (number%10).. 之前启动它。我认为这是因为我将它设置为 += 并且它需要具有值才能这样做。但是,在顶部将其设置为 0 会与我试图制作的计数器混淆。

当我尝试返回计数时,语法也不喜欢,说它不是“长”类型。看来我目前也陷入了 stackoverflow 错误。所以我需要打破递归。

public static long sumLuhnDigits(long number, boolean odd) {
    /// Java IDE said I needed to initiate the variable count but now it won't accumulate properly being set = 0
    long count = 0;

    if (odd == false) {

        count += number % 10;
        number = number / 10;

        odd = true;
        return sumLuhnDigits(number, odd);

    } if (odd == true) {
        count += (number % 10) * 2;
        number = number / 10;
        odd = false;
        return sumLuhnDigits(number, odd);

        /// Here I ran into the problem that count is not the type long, this is also as far as I have gotten     
    } if (number == 0) {
        return count;
    }
}
4

2 回答 2

3
  1. count 绝对是 long 类型

  2. 你没有积累任何东西,因为你正在递归和重置一个局部变量。

您可以尝试两种方法来传递计数(还有其他方法可以做同样的事情)。另外,我怀疑卡号加起来会超过一个整数最大值。

public static int sumLuhnDigits(long number, boolean odd) {
    return sumLuhnDigits(number, odd, 0);
} 

private static int sumLuhnDigits(long number, boolean odd, int count) {
   if (number <= 0) return count;
   if (!odd) {
       count += number % 10;
   } else {
       count += (number % 10) * 2;
  } 
  number = number / 10;
  odd = !odd;
  return sumLuhnDigits(number, odd, count);
} 
于 2017-02-12T22:15:52.367 回答
2

以下不一定是正确答案,但涉及一些代码决策。什么时候计算什么。所以:通用编码。

public static long sumLuhnDigits(long number, boolean odd) {
    if (number == 0) {
        return 0;
    }

    long count;
    if (!odd) {
        count = number % 10;
    } else {
        count = (number % 10) * 2;
    }
    return sumLuhnDigits(number / 10, !odd) + count;
}
  • 最终条件(数字达到0可以先完成。
  • count是一个局部变量。因为它甚至不是一个参数,所以它不会累积任何东西。
  • 但是您可以将其添加到结果中。
  • 布尔值最好不使用== false/true.
于 2017-02-12T22:36:32.267 回答