繁体   English   中英

Java的新手,无法制作Luhn算法

[英]New to Java, having trouble making a Luhn algorithm

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

基本上,我需要创建一个Luhn算法,在其中采用每个值(从右到左),将第二个值加倍(使用Boolean来确定数字是否会加倍),然后将所有值加在一起。 对于前)。 System.out.println(sumLuhnDigits(7992739871005L,false));

将返回72

我遇到的问题涉及“长”型。

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

语法也不喜欢尝试返回count,因为它不是'long'类型。 看来我目前也陷入了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;
    }
}
  1. 计数绝对是长型

  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);
} 

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

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情况下使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM