【问题标题】:Luhn Algorithm sorting outLuhn算法整理
【发布时间】:2020-01-21 16:35:31
【问题描述】:

我正在对这段代码进行排序:

bool checkLuhn(const string& cardNo) 
{ 
    int nDigits = cardNo.length(); 

    int nSum = 0, isSecond = false; 
    for (int i = nDigits - 1; i >= 0; i--) { 

        int d = cardNo[i] - '0'; 

        if (isSecond == true) 
            d = d * 2; 

        nSum += d / 10; 
        nSum += d % 10; 

        isSecond = !isSecond; 
    } 
    return (nSum % 10 == 0); 
} 

有一个我不知道的谜。谷歌搜索过,但仍然是个谜。

那个代码:

if (isSecond == true) 
d = d * 2;

代码程序在哪里检测到它是否可以用 2 分割?我知道如果它不能用 2 分割,程序将它与 2 相乘。

我了解程序的运行原理,但必须有一些方法或东西告诉程序什么是第二。帮帮我。

【问题讨论】:

  • 这是做什么的:isSecond = !isSecond;.
  • isSecondfor 语句之前设置为false,其值在其中更改( isSecond = !isSecond)。
  • 阅读算法 (en.m.wikipedia.org/wiki/Luhn_algorithm)。程序在计算过程中将“每第二位”的值加倍
  • 另外,请感谢您获取代码的网站(超链接或其他内容)Luhn algorithm from GeeksForGeeks
  • 感谢 cmets!是的,我从geeksforgeeks.org/luhn-algorithm 拿走了它。 @ScottHunter 我知道 Luhn 100% 除了 isSecond = !isSecond; 。它如何检查它是否可以与 2 分开?我知道当它不能被 2 分割时,程序将它与 2 相乘,就像在这个 d = d * 2; 中一样。

标签: c# boolean


【解决方案1】:

现在我明白了。

在 for 循环之前 isSecond 为 false,因为 first ordernumber 为 (0)。然后这个isSecond = !isSecond; 将 false 更改为 true。然后轮到第二个 ordernumber (1) 和 isSecond = true; 所以方法将它与 2 相乘。然后它再次变为 false 并且不乘以数字 2。然后它变为 true 并乘以数字 3。

真是个脑筋急转弯:D

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-16
    • 2023-04-05
    • 2013-08-10
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    相关资源
    最近更新 更多