Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading.Channels;
- namespace StringVerification
- {
- public static class IsbnVerifier
- {
- /// <summary>
- /// Verifies if the string representation of number is a valid ISBN-10 identification number of book.
- /// </summary>
- /// <param name="number">The string representation of book's number.</param>
- /// <returns>true if number is a valid ISBN-10 identification number of book, false otherwise.</returns>
- /// <exception cref="ArgumentException">Thrown if number is null or empty or whitespace.</exception>
- public static bool IsValid(string number)
- {
- if (String.IsNullOrWhiteSpace(number))
- {
- throw new ArgumentException("number is null or empty or whitespace.", nameof(number));
- }
- int checkSum = 0;
- string newNumber = number.Replace('-'.ToString(), string.Empty);
- if (newNumber.Length != 10)
- {
- return false;
- }
- for (int i = 0; i < newNumber.Length - 1; i++)
- {
- if (CharToInt(newNumber[i]) == -1 || CharToInt(newNumber[i]) == 10)
- {
- return false;
- }
- checkSum += CharToInt(newNumber[i]) * (10 - i);
- }
- if (CharToInt(newNumber[^1]) == -1)
- {
- return false;
- }
- checkSum += CharToInt(newNumber[^1]);
- return checkSum % 11 == 0;
- }
- private static int CharToInt(char digit) =>
- digit switch
- {
- '0' => 0,
- '1' => 1,
- '2' => 2,
- '3' => 3,
- '4' => 4,
- '5' => 5,
- '6' => 6,
- '7' => 7,
- '8' => 8,
- '9' => 9,
- 'X' => 10,
- _ => -1
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement