1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-25 10:11:56 +01:00

5kyu: add ISBN-10 Validation

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-08-03 22:31:25 +02:00
parent 54483a1651
commit 5dea8c097c
Signed by: mfocko
GPG key ID: 7C47D46246790496
2 changed files with 47 additions and 0 deletions

View file

@ -0,0 +1,46 @@
#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;
}

View file

@ -88,6 +88,7 @@
- [Greed is Good](https://www.codewars.com/kata/5270d0d18625160ada0000e4) - [solution](5kyu/greed_is_good) - [Greed is Good](https://www.codewars.com/kata/5270d0d18625160ada0000e4) - [solution](5kyu/greed_is_good)
- [Snakes and Ladders](https://www.codewars.com/kata/587136ba2eefcb92a9000027) - [solution](5kyu/snakes_and_ladders) - [Snakes and Ladders](https://www.codewars.com/kata/587136ba2eefcb92a9000027) - [solution](5kyu/snakes_and_ladders)
- [The Clockwise Spiral](https://www.codewars.com/kata/536a155256eb459b8700077e) - [solution](5kyu/the_clockwise_spiral) - [The Clockwise Spiral](https://www.codewars.com/kata/536a155256eb459b8700077e) - [solution](5kyu/the_clockwise_spiral)
- [ISBN-10 Validation](https://www.codewars.com/kata/51fc12de24a9d8cb0e000001) - [solution](5kyu/isbn10_validation)
### Python ### Python