mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-21 16:13:47 +01:00
5kyu: add ISBN-10 Validation
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
54483a1651
commit
5dea8c097c
2 changed files with 47 additions and 0 deletions
46
5kyu/isbn10_validation/solution.c
Normal file
46
5kyu/isbn10_validation/solution.c
Normal 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;
|
||||
}
|
|
@ -88,6 +88,7 @@
|
|||
- [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)
|
||||
- [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
|
||||
|
||||
|
|
Loading…
Reference in a new issue