记录一个个人觉得比较有趣的题目,LeetCode的第9题。
题目如下:
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
下面代码是C语言版本:
bool isPalindrome(int x){
//首先排除负数
if(x<0)
return false;
//个位数都是回文数
else if(x>=0 && x<=9)
return true;
//两位数以上的数,我将整数当字符串进行对比判断。
else
{
//因为题目给出数的范围是正负2的31次方-1,所以这里只需要用一个长度为10的数组就能存完所有数。
int temp[10];
int index = 0; //数组的起点。
int chushu = x; //这是除数,这里直接用拼音命名了。。。。。。
while(chushu/10>0)
{
int yushu = chushu%10;//余数(拼音命名。。。)
temp[index] = yushu;
chushu = chushu/10;
index++;
}
temp[index] = chushu;//数的最高位
int i = 0;
int j = index;
//对存入数组的数进行对比。
while(i<=j)
{
if(temp[i]==temp[j])
{
i++;
j--;
continue;
}
if(temp[i]!=temp[j])
return false;
}
if(i>=j)//当i>j是表明已经全部对数都对比完了且都相等
return true;
}
return 0;
}