Home > Article > Backend Development > Three algorithms for finding palindrome numbers in C language
The article shared by the editor today is three algorithms for describing palindrome numbers in C language. It has certain reference value. If you are interested in palindrome numbers in C language, you can take a look. I hope it will be helpful to you.
* I would like to ask: How many n-digit palindromes are there? Please write a recursive function to solve this problem! ! !
##Input:
3
Output:
90
5
Output:
900
10
Output:
90000 **
8
Output:
9000
1
Output:
10
mathematical relations, directly determine the number of digits and calculate the number of palindromes within this digit;
1. 第一种思路:
#include <stdio.h> #include <math.h> int reverse(long int i,long int *terminate) //递归函数求数值的逆序 { if (i<=0){ //递归出口 return 1; } else{ *terminate*=10; //每次乘10升位数 *terminate+=i%10; //加上个位 reverse(i/10,terminate); //递归每次规模缩小 } return 1; } int main () { int n; scanf ("%d",&n); //读入一个n,表示n位整数 long int i; int count=0; if (n==1){ //如果等于1,则有10个(0-9都是),特殊处理; printf ("10"); return 0; } for (i=pow(10,n-1);i<pow(10,n);i++){ //从第一个n位数开始(10^(n-1)),到(10^n)-1 long int terminate=0; //定义一个逆序目标数 reverse(i,&terminate); //把i和逆序目标数传入 if (terminate==i){ //逆序后还和原数相等,则可计数 count++; } } printf ("%d",count); //输出个数 return 0; }
2. 第二种思路:
#include <stdio.h> #include <math.h> int judge(int i,int n) { int first,last; if (n<=1){ //规模减小,直到n为1(偶数)或者0 return 1; } else{ first=i/pow(10,n-1); //头位数字 last=i%10; //末位数字 if (first!=last){ //头位末尾不一样直接退出 return 0; } int tem=pow(10,n-1); judge(i%tem/10,n-2); //剔除头尾剩下中间,位数减二 } } int main () { int n; scanf("%d",&n); if (1==n){ printf ("10"); return 0; } int i; int count=0; long long low=pow(10,n-1); //循环入口 long long high=pow(10,n); //循环出口 for (i=low;i<high;i++){ if ( judge(i,n)==1){ //判断i是否为回文,计数 count++; } } printf ("%d",count); return 0; }
3. 第三种思路:
#include <stdio.h> #include <math.h> int main (){ int n; scanf ("%d",&n); int ji=9*pow(10,n/2),ou=9*pow(10,n/2-1); if (n==1){ printf ("10"); } else if (n==2){ printf ("%d",9); } else if (n%2==1){ printf ("%d",ji); } else if (n%2==0){ printf("%d",ou); } return 0; }
The above is the detailed content of Three algorithms for finding palindrome numbers in C language. For more information, please follow other related articles on the PHP Chinese website!