Created
November 4, 2014 03:07
-
-
Save jgrar/0c63c8582ce10b71ab53 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
/* returns: non-zero if s points to a sequence | |
* of characters that is palindromic, 0 if not | |
*/ | |
int is_palindrome (char *s) { | |
int N, n; | |
int i; | |
N = strlen(s) - 1; | |
n = N - 1 / 2; | |
if (n < 0) { | |
return 0; | |
} | |
for (i = 0; i <= n; i++) { | |
if (s[i] != s[N - i]) { | |
return 0; | |
} | |
} | |
return 1; | |
} | |
#ifndef NO_TEST | |
struct unit { | |
char *s; | |
int r; | |
}; | |
static struct unit tests[] = { | |
{ "racecar", 1 }, | |
{ "racecars", 0 }, | |
{ "aabcc", 0 }, | |
{ "aabbaa", 1 }, | |
{ "a", 1 }, | |
{ "aa", 1 }, | |
{ "aba", 1 }, | |
{ "abba", 1 }, | |
{ "abcba", 1 }, | |
{ "", 0 }, | |
}; | |
int main () { | |
int i, r; | |
for (i = 0; i < sizeof tests / sizeof tests[0]; i++) { | |
r = is_palindrome(tests[i].s); | |
if (r != tests[i].r) { | |
fprintf(stderr, "%d: FAILED: expected is_palindrome(%s) == %d, got %d\n", | |
i + 1, tests[i].s, tests[i].r, r); | |
exit(EXIT_FAILURE); | |
} | |
} | |
puts("PASSED"); | |
exit(EXIT_SUCCESS); | |
} | |
#endif /* NO_TEST */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment