主题:[原创]分享一个回文数函数
/*
* palindrome.c - summary how many palindrome numbers from 1 to SIZE
*
* CopyRight (c) 2010-07-31 by and <manzsc@live.cn>
*/
#include <stdio.h>
#include <string.h>
#define SIZE 10000 // define a number
#define BASE 10 // carry bit :decimal system
/*
* is_palindrome() - judge a number is or not palindrome
* @str: the input string
*
* return value: 0 - string is not palindrome
* 1 - string is palindrome
*/
int is_palindrome(char *str)
{
int i, len;
len = strlen(str);
for (i = 0; i < len / 2; i++)
{
/*
* compare str[i] and str[len-i-1]
* if not equal, return 0
*/
if (str[i] != str[len-i-1])
return 0;
}
return 1;
}
/*
* itora() - change a number to string
* @num: the interger number
* @str: the result string
* return value: default 0
*/
int itora(int num, char *str)
{
int div, rest;
int i = 0;
div = num;
/* resursive divide and get mod number to rest */
while (div)
{
rest = div % BASE;
div = div / BASE;
/* save rest number into str[i] */
str[i++] = rest + '0';
}
str[i] = '\0';
return 0;
}
int main(void)
{
int i;
int counter = 0;
char str[10]; // num define by SIZE
printf("***********palindrome demo test*********** \n");
for (i = 1; i <= SIZE; i++)
{
/* change interger num to string */
itora(i, str);
//printf("<itora> str = %s \n", str);
/* judge the number is palindrome? */
if (is_palindrome(str))
{
counter++;
printf("%d : str = %s \n", counter, str);
}
}
return 0;
}
* palindrome.c - summary how many palindrome numbers from 1 to SIZE
*
* CopyRight (c) 2010-07-31 by and <manzsc@live.cn>
*/
#include <stdio.h>
#include <string.h>
#define SIZE 10000 // define a number
#define BASE 10 // carry bit :decimal system
/*
* is_palindrome() - judge a number is or not palindrome
* @str: the input string
*
* return value: 0 - string is not palindrome
* 1 - string is palindrome
*/
int is_palindrome(char *str)
{
int i, len;
len = strlen(str);
for (i = 0; i < len / 2; i++)
{
/*
* compare str[i] and str[len-i-1]
* if not equal, return 0
*/
if (str[i] != str[len-i-1])
return 0;
}
return 1;
}
/*
* itora() - change a number to string
* @num: the interger number
* @str: the result string
* return value: default 0
*/
int itora(int num, char *str)
{
int div, rest;
int i = 0;
div = num;
/* resursive divide and get mod number to rest */
while (div)
{
rest = div % BASE;
div = div / BASE;
/* save rest number into str[i] */
str[i++] = rest + '0';
}
str[i] = '\0';
return 0;
}
int main(void)
{
int i;
int counter = 0;
char str[10]; // num define by SIZE
printf("***********palindrome demo test*********** \n");
for (i = 1; i <= SIZE; i++)
{
/* change interger num to string */
itora(i, str);
//printf("<itora> str = %s \n", str);
/* judge the number is palindrome? */
if (is_palindrome(str))
{
counter++;
printf("%d : str = %s \n", counter, str);
}
}
return 0;
}