提示要求我在下面拥有公共静态并且只使用递归。这是我使用 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;
}
}