Created
May 12, 2016 17:39
-
-
Save amantix/fac63e9d386b843f3bc45f6bb8978d07 to your computer and use it in GitHub Desktop.
Check sum algorithm implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
namespace CSLanguage | |
{ | |
class Program | |
{ | |
static int DigitsSum(string digits) | |
{ | |
int tmp = 0; | |
foreach (char c in digits) | |
tmp += c - '0'; | |
return tmp; | |
} | |
static int CheckSum(int number) | |
{ | |
var digits = number.ToString().ToArray(); | |
for (var i = digits.Length - 1; i >= 0; i -= 2) | |
{ | |
var str = ((digits[i] - '0') * 2).ToString(); | |
digits[i] = (char)(DigitsSum(str) + '0'); | |
} | |
var result = 10 - DigitsSum(new string(digits)) % 10; | |
return result; | |
} | |
static int LinqCheckSum(int number) | |
{ | |
var result= | |
number.ToString() | |
.Reverse() | |
.Select(x => x - '0') | |
.Zip(Enumerable.Range(0, 9), (x, y) => new {x, y}) | |
.Select(x => x.y%2 == 0 ? x.x*2 : x.x) | |
.Select(x => x.ToString().Sum(y => y - '0')) | |
.Reverse() | |
.Sum(); | |
return 10 - result%10; | |
} | |
static void Main(string[] args) | |
{ | |
int x = int.Parse(Console.ReadLine()); | |
Console.WriteLine(CheckSum(x)); | |
Console.WriteLine(LinqCheckSum(x)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment