簡體   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