Description
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Examples
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.
解题思路
正常思路就是把int转换为String,然后两边开始往中间对应
但是这样耗时很大(我用了188ms),代码如下:
class Solution {
public boolean isPalindrome(int x) {
Integer a = x;
int i;
String str1 = a.toString();
//String str2 = new StringBuffer(str1).reverse().toString();
int len = str1.length();
for(i = 0; i < len / 2 + 1; i++){
if(str1.charAt(i) != str1.charAt(len - i - 1))
break;
}
if(i == len / 2 + 1)
return true;
return false;
}
}
后来把String转换为char数组,发现省去了很大的时间(114ms)
class Solution {
public boolean isPalindrome(int x) {
Integer a = x;
int i;
String str1 = a.toString();
char[] ch = str1.toCharArray();
int len = str1.length();
for(i = 0; i < len / 2 + 1; i++){
if(ch[i] != ch[len - i - 1])
return false;
}
return true;
}
}
其他Solution
题目上给了个follow up:
- Coud you solve it without converting the integer to a string?
然后给出了解法:
如果是反转一个int数据的话可能会出现溢出的情况(1111111119),所以选择反转半个int,即后半块反转之后应该等于前半块
如1221,从第二个数切开,变成12、21,把21反转,会变成12,和前半块相同
现在要考虑怎么反转后半块的问题
很容易可以想到提取最后一个数字可以用num % 10,然后对num / 10,就可以把尾数消除,循环进行就可以核对所有的num了
然后是怎么判断是否到了中点的问题,可以设置一个反转数,每次都*10,当不断被/10的数字比这个数小的时候,就可以发现找到了中点
java代码如下:
class Solution {
public boolean isPalindrome(int x) {
if(x < 0 || (x % 10 == 0 && x != 0))
return false;
int comp1 = 0;
while(comp1 < x){
comp1 = x % 10 + comp1 * 10;
x = x / 10;
}
if(comp1 == x || comp1 / 10 == x)
return true;
return false;
}
}
注意点:
- 在第一个判断的时候要注意把x是10的倍数的情况单拎出来考虑,因为如果对10(或10的倍数)做反转,位数就不对了(从而不能凑到中点),且10的倍数的reverse都要以0开头,除了0之外别的都不符合,所以索性全放成false
- 在最后compare的时候,有两种可能性,一种是位数是双数,这种情况判断两位数相等与否就行,一种是单数,这种情况可以把中间那位去了(comp1 / 10)然后再与修改后的x进行比较
- 举个例子:1221,在第一步不满足情况,第二步comp = 12,x = 12,x = comp,退出循环,进入第三步,两个相等,返回true
- 再举个例子12121,第一步不满足情况,第二部comp = 121,x = 12,x = comp / 10(1处在中点,不用算),两个相等,返回true
其他
吐槽下leetcode的判分系统,同样的代码出来的运行时间会不一样的hmmmm(114和177),大概是因为人多了卡?而且最后一个方法应该最快(毕竟少了tostring的转换)居然是最费时的???(178ms)