【发布时间】: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;. -
isSecond在for语句之前设置为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;中一样。