1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-09 11:09:07 +01:00
CodeWars/5kyu/isbn10_validation/solution.c
Matej Focko 5dea8c097c
5kyu: add ISBN-10 Validation
Signed-off-by: Matej Focko <mfocko@redhat.com>
2022-08-03 22:31:25 +02:00

46 lines
1.1 KiB
C

#include <assert.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
static bool check_digit(char digit, int idx, int* sum)
{
if (!isdigit(digit) && (idx != 9 || digit != 'X')) {
return false;
}
*sum += (idx + 1) * ((digit == 'X') ? 10 : (digit - '0'));
return true;
}
bool is_valid_ISBN_10(const char* ISBN)
{
if (ISBN == NULL) {
return false;
}
int i, sum = 0;
for (i = 0; i < 10; i++) {
if (!check_digit(ISBN[i], i, &sum)) {
return false;
}
}
return i == 10 && ISBN[i] == '\0' && sum % 11 == 0;
}
int main(void)
{
assert(is_valid_ISBN_10("1112223339") == true);
assert(is_valid_ISBN_10("048665088X") == true);
assert(is_valid_ISBN_10("1293000000") == true);
assert(is_valid_ISBN_10("1234554321") == true);
assert(is_valid_ISBN_10("1234512345") == false);
assert(is_valid_ISBN_10("1293") == false);
assert(is_valid_ISBN_10("X123456788") == false);
assert(is_valid_ISBN_10("ABCDEFGHIJ") == false);
assert(is_valid_ISBN_10("XXXXXXXXXX") == false);
assert(is_valid_ISBN_10("048665088XZ") == false);
return 0;
}