本文介绍了有人可以用luhn算法解释这段代码的含义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞!private static bool IsValidNumber(string number){ int[] DELTAS = new int[] { 0, 1, 2, 3, 4, -4, -3, -2, -1, 0 }; int checksum = 0; char[] chars = number.ToCharArray(); for (int i = chars.Length - 1; i > -1; i--) { int j = ((int)chars[i]) - 48; checksum += j; if (((i - chars.Length) % 2) == 0) checksum += DELTAS[j]; } return ((checksum % 10) == 0);} 有人能告诉我,我们为什么使用Can someone tell me, why we are usingint[] DELTAS = new int[] { 0, 1, 2, 3, 4, -4, -3, -2, -1, 0 }; 是否使用上述代码? 最后一个代码whats the use of above code?In last codechecksum += DELTAS[j]; 我们基本上是添加信用卡号码,这些号码是{0,1,2,3,4,-4,-3,-2,-1,0}逐一。 这看起来更像是一个数学问题,而不是编码问题。 但是,我被困在这一部分。 提前谢谢we are basically adding , credit card number with these number { 0, 1, 2, 3, 4, -4, -3, -2, -1, 0 } one by one.This seems more like a mathematical question rather than coding question.But, i am stuck in this part.Thanks in advance推荐答案从最右边的数字,即校验位,向左移动,每秒数字的值加倍;如果此倍增操作的乘积大于9(例如,8×2 = 16),则将产品的数字相加(例如,16:1 + 6 = 7,18:1 + 8 = 9)。From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then sum the digits of the products (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9). 确实DELTAS数组项代表加倍数字的总和与数字本身的差异:indeed the DELTAS array items represent the difference of the 'sum of digits of doubled number' and the number itself:0 => 0 * 2 = 0 => DELTAS[0] = 01 => 1 * 2 = 2 => DELTAS[1] = 1 (because 2 - 1 = 1)...6 => 6 * 2 = 12 => 1 + 2 = 3 => DELTAS[6]=-3 (because 3 - 6 = -3)...public static intLuhn( string Value){ int sum = 0 ; int mul = 1 ; for ( int i = Value.Length - 1 ; i >= 0 ; i-- ) { int val = (int) Value [ i ] - 48 ; if ( val >= 0 && val < 10 ) { val *= mul ; sum += val / 10 + val % 10 ; mul ^= 3 ; } } return ( sum % 10 ) ;} 此外,请考虑使用SPACE或HYPHEN传入数字时所发布的代码会发生什么。 一些基准测试结果:Also, consider what happens with the code you posted when a number is passed in with SPACEs or HYPHENs.Some benchmarking results:1000000 in 00:00:00.2791342 -- What you posted1000000 in 00:00:00.2380398 -- What you posted, without the ridiculous ToCharArray1000000 in 00:00:00.6797738 -- What you posted, with char[] chars = number.Where ( x => x >= '0' && x <= '9' ).ToArray();1000000 in 00:00:00.0848604 -- What you posted, with static DELTAS1000000 in 00:00:00.0689142 -- What you posted, with static DELTAS, without the ridiculous ToCharArray1000000 in 00:00:00.0681335 -- What you posted, with static two-dimensional DELTAS, without the ridiculous ToCharArray1000000 in 00:00:00.0951645 -- What I posted1000000 in 00:00:00.0818445 -- What I posted, without the test for non-digits 这篇关于有人可以用luhn算法解释这段代码的含义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-19 13:53