C# Luhn算法排序
我正在排序此代码:C# Luhn算法排序,c#,boolean,C#,Boolean,我正在排序此代码: 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)
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
我理解程序的工作原理,但必须有某种方法或东西告诉程序这是什么。帮帮我,伙计们。现在我明白了
在for循环之前,isSecond为false,因为第一个ordernumber为(0)。那么这个isSecond=!第二代码>将false更改为true。然后轮到第二个ordernumber(1)和isSecond=true代码>所以方法将其乘以2。然后它再次变为假,不乘以数字2。然后它变为真,乘以数字3
真是个脑筋急转弯:这就是它的作用:isSecond=!第二
isSecond
在for
语句之前设置为false
,其值在语句内部更改(即isSecond=!isSecond
)。请阅读算法()。在计算过程中,该程序将“每两位数”的值翻一番。因此,请对您从中获得代码的网站(超链接或其他)给予信任。谢谢您的评论!是的,我从你那儿拿的@ScottHunter我100%了解Luhn除了isSecond=!第二代码>。它如何检查它是否可与2拆分?我知道当它不能被2分割时,程序用2乘以它,就像下面的d=d*2代码>。