← All problems · Pointers & Strings
Check Whether a String Is a Palindrome
Return 1 if a NUL-terminated string reads identically forward and backward, otherwise 0. Compare bytes exactly, including case and spaces.
Implement int is_palindrome(const char *s).
Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Compare the two ends and move inward.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
int is_palindrome(const char *s)
{
size_t n=strlen(s);
for(size_t i=0;i<n/2;++i)if(s[i]!=s[n-1-i])return 0;
return 1;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <climits>
int is_palindrome(const char *s)
{
std::size_t n=std::strlen(s);
for(std::size_t i=0;i<n/2;++i)if(s[i]!=s[n-1-i])return 0;
return 1;
}
Only half of the string needs comparison. Empty and one-character strings are palindromes.
solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
CHECK(is_palindrome("ABCKCBA")==1);
CHECK(is_palindrome("abba")==1);
CHECK(is_palindrome("abc")==0);
CHECK(is_palindrome("")==1);
CHECK(is_palindrome("Aa")==0);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}