C language realizes whether the input number is a palindrome

Input a positive integer from the keyboard (the number of digits is less than or equal to 10), and judge whether it is a palindrome (the palindrome is to arrange the digits of the natural number n in reverse order to obtain the natural number n1, if n1 and n are equal, then n is called Number of palindrome, for example: 12321)

The program code is as follows:

#include <stdio.h>
#include <math.h>

// 定义函数getLength,计算正整数 num 的位数
int getLength(long int num){
    
    
	 
	int found,length;
	found = 0;
	length = 10; //设置正整数的位数小于或等于10
	if(num==0){
    
    
	  return 1;
	}
	while(found == 0){
    
    
		if(num/(int)pow(10,length-1)>0){
    
      // 库函数POW(10,length-1) 的功能是计算10 的(length-1) 次幂
			found = 1;
		}else{
    
    
			length -= 1;
		}
	}
	return (length); // 返回正整数num 的位数

}

int isHuiWenShu(long int num){
    
     // 定义函数 是否为回文,判断正整数num 是否是回文数

	long int n; // 定义变量n 保存从键盘输入的正整数
	int left; // 定义 left 保存正整数最左边的数字
	int right;// 定义变量right 保存正整数最右边的数字
	int i; // 定义变量 i,保存正整数的位数
	int flag;// 定义变量 flag 保存是否是回文数的标志。若不是回文数,则flag=1;否则flag=0
	i = getLength(num); // 调用函数getLength 将正整数num 的位数赋予变量 i
	n = num;
	flag = 0;
	while(i>1&&flag==0){
    
    
		left = n/(int)pow(10,i-1);//将正整数 n 当前最左边的数字赋予变量 left	
		right = n%10; // 将正整数n 当前最右边的数 赋予变量 right
		n = n %(int)pow(10,i-1)/10;
		i -=2;
		if(left!=right){
    
     // 若正整数n 当前最左边和最右边的数字不相等,则不是回文数,即变量flag 赋值 1
			flag=1;
		}
	}
	if(flag == 0){
    
    
		return 1;//若不是回文 则返回1
	}else{
    
    
		return 0;//若是回文 则返回0
	}
}

int main(){
    
    
	long int num;
	scanf("%ld",&num);
	if(isHuiWenShu(num)){
    
    
		printf("%d 是回文数\n",num);
	}else{
    
    
		printf("%d 不是回文数\n",num);
	}

	return 0;
}

Guess you like

Origin blog.csdn.net/G_whang/article/details/113053600