本文共 2514 字,大约阅读时间需要 8 分钟。
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? 跟进:试着解决这个问题,而不将整型数据转成字符串。int iValue;//整型数baichar sz[10];//字符串sprintf(sz, "%d", iValue);//这句需要头文件du#include
功用:将要输出的东西按照相应的格式存放到第一个参数的字符串中。
itoa(iValue, sz, 10); //这句需要头文件#include
功用:直接将整型数转化成字符串,会自动将数字转成16进制,然后将16进制的整型数字变成字符串
#include#include 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; }}
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; }
转载地址:http://sggpb.baihongyu.com/