Advertisement
yahorrr

Untitled

Oct 3rd, 2022
759
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.99 KB | None | 0 0
  1. using System;
  2. using System.Threading.Channels;
  3.  
  4. namespace StringVerification
  5. {
  6.     public static class IsbnVerifier
  7.     {
  8.         /// <summary>
  9.         /// Verifies if the string representation of number is a valid ISBN-10 identification number of book.
  10.         /// </summary>
  11.         /// <param name="number">The string representation of book's number.</param>
  12.         /// <returns>true if number is a valid ISBN-10 identification number of book, false otherwise.</returns>
  13.         /// <exception cref="ArgumentException">Thrown if number is null or empty or whitespace.</exception>
  14.         public static bool IsValid(string number)
  15.         {
  16.             if (String.IsNullOrWhiteSpace(number))
  17.             {
  18.                 throw new ArgumentException("number is null or empty or whitespace.", nameof(number));
  19.             }
  20.  
  21.             int checkSum = 0;
  22.             string newNumber = number.Replace('-'.ToString(), string.Empty);
  23.  
  24.             if (newNumber.Length != 10)
  25.             {
  26.                 return false;
  27.             }
  28.  
  29.             for (int i = 0; i < newNumber.Length - 1; i++)
  30.             {
  31.                 if (CharToInt(newNumber[i]) == -1 || CharToInt(newNumber[i]) == 10)
  32.                 {
  33.                     return false;
  34.                 }
  35.  
  36.                 checkSum += CharToInt(newNumber[i]) * (10 - i);
  37.             }
  38.  
  39.             if (CharToInt(newNumber[^1]) == -1)
  40.             {
  41.                 return false;
  42.             }
  43.  
  44.             checkSum += CharToInt(newNumber[^1]);
  45.  
  46.             return checkSum % 11 == 0;
  47.         }
  48.  
  49.         private static int CharToInt(char digit) =>
  50.             digit switch
  51.             {
  52.                 '0' => 0,
  53.                 '1' => 1,
  54.                 '2' => 2,
  55.                 '3' => 3,
  56.                 '4' => 4,
  57.                 '5' => 5,
  58.                 '6' => 6,
  59.                 '7' => 7,
  60.                 '8' => 8,
  61.                 '9' => 9,
  62.                 'X' => 10,
  63.                 _ => -1
  64.             };
  65.     }
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement