题目描述
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
判定一个整型的数字是否是回文。一个回文的正数正反读过来都是相同的
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
跟进:试着解决这个问题,而不将整型数据转成字符串。
知识补充
- sprintf(字符串指针,“数据类型”,对应数据类型的变量)
int iValue;//整型数bai
char sz[10];//字符串
sprintf(sz, "%d", iValue);//这句需要头文件du#include <stdio.h>
功用:将要输出的东西按照相应的格式存放到第一个参数的字符串中。
- itoa(整型数,字符串首地址指针,字符串的长度)16进制数字构成的字符串
itoa(iValue, sz, 10); //这句需要头文件#include <ctype.h>
功用:直接将整型数转化成字符串,会自动将数字转成16进制,然后将16进制的整型数字变成字符串
问题思考
- 方法一:转成字符串,用头指针和尾指针,从两边分别向中间进行比对
- 方法二:将原来的数字反转并保存到新的数字中,直接比较两个数是否相同
我的代码
- 方法一:
#include <stdio.h>
#include <stdlib.h>
typedef enum {
false,true} bool;
bool isPalindrome(int x);
int main()
{
//今日份的了leetcode——palindrome number 回数
int test = 11;
int res = isPalindrome(test);
printf("%d \n",res);
return 0;
}
bool isPalindrome(int x)
{
char sz[20];
sprintf(sz,"%d",x);
printf("%s \n",sz);
char *start = sz,*end = sz;
while(*end)
{
end ++;
}
end--;
while(start <= end)
{
if(*start == *end)
{
start++;
end--;
}
else
{
return false;
}
}
return true;
}
- 方法二:
bool isPalindrome(int x){
int y = x,temp ;
long res = 0;
if(x < 0)
{
return false;
}
do{
temp = y % 10;
res = res *10 + temp;
y /= 10;
}while(y != 0);
printf("%d \n",res);
if(res == x)
{
return true;
}
else
{
return false;
}
}
分析总结
- 对于数字而言,可以有效模拟出栈和入栈,出栈就是“%10”,同时原数“/10”。入栈就是原数“*10”,加上后来的数字
- 对于将整型数字转成字符串,建议用sprintf()函数
solution的分析
- 首先题目已经说明不可以将整型数字转成字符串,转成字符串会产生很多的非永久的存储空间。
- 然后,如果将原来的数字进行反转,直接和原来的数字进行比较会出现越界的情况
- 最后,为了防止越界,但又不创建字符串,就反转原来的数字一半,在和剩余的另外一半进行比较。
代码实现
- 步骤一:不是回文的:负数 或者 最后一位是零而末尾不是零的
- 步骤二:反转原数的一半,当且仅当原数 “<="反转之后的数字
- 步骤三:判定是否相等:原数 == 反转之后的数字 或者 反转之后的数字 / 10 == 原数(针对12321之类的,偶数的个数)
代码实现
int revert = 0;
if( x < 0 || (x% 10 == 0 && x != 0))
{
return false;
}
while(x > revert)
{
revert = revert * 10 + x % 10;
x /= 10;
}
if(x == revert ||(x == (revert / 10)))
{
return true;
}
总结
- 思考问题的方式有待改善