Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace SRP.ControlDigit
- {
- public static class ControlDigitAlgo
- {
- public static int Upc(long number)
- {
- return number.GetSum(3, factor => 4 - factor).ControlDigit(10);
- }
- public static int Isbn10(long number)
- {
- var Isbn10ControlDigit = number.GetSum(2, factor => factor + 1).ControlDigit(11);
- if (Isbn10ControlDigit == 10)
- {
- return 'X';
- }
- return Isbn10ControlDigit + '0';
- }
- public static int Luhn(long number)
- {
- return number.GetSumLuhn(2, factor => factor % 2 == 0 ? 1 : 2).ControlDigit(10);
- }
- }
- public static class Extensions
- {
- public static int GetSum(this long number, int factor, Func<int, int> nextPosition)
- {
- var digitsSum = 0;
- do
- {
- digitsSum += factor * (int)(number % 10);
- number /= 10;
- factor = nextPosition(factor);
- } while (number > 0);
- return digitsSum;
- }
- public static int GetSumLuhn(this long number, int factor, Func<int, int> nextPosition)
- {
- var digitsSum = 0;
- while (number > 0)
- {
- if (factor * (int)(number % 10) > 9)
- {
- digitsSum += factor * (int)(number % 10) - 9;
- }
- else
- {
- digitsSum += factor * (int)(number % 10);
- }
- number /= 10;
- factor = nextPosition(factor);
- }
- return digitsSum;
- }
- public static int ControlDigit(this int digitsSum, int module)
- {
- if (digitsSum % module == 0) return 0;
- return module - digitsSum % module;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement