Advertisement
VssA

контрольный выстрел

Apr 14th, 2024
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. namespace SRP.ControlDigit
  6. {
  7. public static class ControlDigitAlgo
  8. {
  9. public static int Upc(long number)
  10. {
  11. return number.GetSum(3, factor => 4 - factor).ControlDigit(10);
  12. }
  13.  
  14. public static int Isbn10(long number)
  15. {
  16. var Isbn10ControlDigit = number.GetSum(2, factor => factor + 1).ControlDigit(11);
  17. if (Isbn10ControlDigit == 10)
  18. {
  19. return 'X';
  20. }
  21. return Isbn10ControlDigit + '0';
  22. }
  23.  
  24. public static int Luhn(long number)
  25. {
  26. return number.GetSumLuhn(2, factor => factor % 2 == 0 ? 1 : 2).ControlDigit(10);
  27. }
  28. }
  29.  
  30. public static class Extensions
  31. {
  32. public static int GetSum(this long number, int factor, Func<int, int> nextPosition)
  33. {
  34. var digitsSum = 0;
  35. do
  36. {
  37. digitsSum += factor * (int)(number % 10);
  38. number /= 10;
  39. factor = nextPosition(factor);
  40. } while (number > 0);
  41. return digitsSum;
  42. }
  43.  
  44. public static int GetSumLuhn(this long number, int factor, Func<int, int> nextPosition)
  45. {
  46. var digitsSum = 0;
  47. while (number > 0)
  48. {
  49. if (factor * (int)(number % 10) > 9)
  50. {
  51. digitsSum += factor * (int)(number % 10) - 9;
  52. }
  53. else
  54. {
  55. digitsSum += factor * (int)(number % 10);
  56. }
  57. number /= 10;
  58. factor = nextPosition(factor);
  59. }
  60. return digitsSum;
  61. }
  62.  
  63. public static int ControlDigit(this int digitsSum, int module)
  64. {
  65. if (digitsSum % module == 0) return 0;
  66. return module - digitsSum % module;
  67. }
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement