算法分析---回文数推断

有这样一类数字,他们顺着看和倒着看是同样的数。比如:111112212332等。这种数字就称为:回文数字。

回文数的推断有多种算法,直观一点的就是将数字顺序颠倒后再与原数字进行比較,假设相等说明该数字是回文数字。怎样颠倒数字的顺序便是难点。

比方一个数12345。

12345 % 10 得到的是个位上的5

12345 / 10 得到1234

1234 % 10 得到十位上的4

1234 / 10 得到123

123 % 10 得到百位上的3

123 / 10 得到12

12 % 10 得到千位上的2

12 / 10 得到1

1 % 10 得到万位上的1

可见通过求余运算来求各个位上的数,通过除法运算来降位(指的是由万位降到千位。千位再降到百位)


如今開始颠倒数字

第一步:

12345 % 10 = 5;求个位上的数

12345 / 10 =1234;降位

第二步:

1234 % 10 = 4;求十位上的数

1234 / 10 = 123; 降位

5 * 10 + 4 = 54。開始颠倒

第三步:

123 % 10 = 3。 求百位上的数

123 / 10 = 12; 降位

54 * 10 + 3 = 543; 继续颠倒

第四步:

12 % 10 = 2; 求千位上的数

12 / 10 = 1; 降位

543 * 10 + 2 = 5432; 继续颠倒

第五步:

1 % 10 = 1; 求万位上的数  

1 / 10 = 0; 降位

5432 * 10 + 1 = 54321; 颠倒完成

#include <stdio.h>

int IsPalindrome(int iNumber); 

void main(){
	if(IsPalindrome(121)){
		printf("是回文数
");
	}
	else{
		printf("不是回文数
");
	}


}


int IsPalindrome(int iNumber){  //推断是否为回文数的函数
	int temp=0;
	int number = iNumber;
	while(number){   //颠倒数后保存到temp中
		temp=temp*10+(number%10);
		number=number/10;
	}
	if(iNumber==temp) //是回文数,返回1
	    return 1;
	else
		return 0;
}


原文地址:https://www.cnblogs.com/jzssuanfa/p/7375494.html