简体   繁体   English

Luhn算法整理

[英]Luhn Algorithm sorting out

I am sorting this code:我正在整理这段代码:

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

There is one mystery what i do not know.有一个我不知道的奥秘。 Have googled, but still mystery.已经谷歌搜索,但仍然是个谜。

That code:那个代码:

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

Where on the code program detects is it splitable with 2?代码程序检测到它是否可以与 2 拆分? I understand if it's not splitable with 2, program multiply it with 2.我知道如果它不能用 2 拆分,则将其与 2 相乘。

I understand operational principle of the program, but there must be some method or something which tells program what is that isSecond.我了解程序的运行原理,但是必须有某种方法或某些东西可以告诉程序什么是第二。 Help me guys.帮帮我吧伙计们。

Now i understand it.现在我明白了。

Before the for loop isSecond is false because first ordernumber is (0).在 for 循环之前 isSecond 是假的,因为第一个 ordernumber 是 (0)。 Then this isSecond = !isSecond;那么这个isSecond = !isSecond; change false to true.把假改成真。 Then it's turn of the second ordernumber (1) and isSecond = true;然后轮到第二个isSecond = true; (1) 和isSecond = true; so method multiplies it with 2. And then it goes false again and not multiplies number 2. Then it goes true and multiply number 3.所以方法将它与 2 相乘。然后它再次变为假而不是乘以数字 2。然后它变为真并乘以数字 3。

What a brain-teaser :D真是脑筋急转弯:D

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

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