Skip to content

Instantly share code, notes, and snippets.

@amantix
Created May 12, 2016 17:39
Show Gist options
  • Save amantix/fac63e9d386b843f3bc45f6bb8978d07 to your computer and use it in GitHub Desktop.
Save amantix/fac63e9d386b843f3bc45f6bb8978d07 to your computer and use it in GitHub Desktop.
Check sum algorithm implementation
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