mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-09 11:09:07 +01:00
46 lines
1.1 KiB
C
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;
|
|
}
|