前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
参考了一个思路,真的是机智呀,将余数反向保存起来判断相等吗。Your runtime beats 40.81% of java submissions.
public class Solution {
public boolean isPalindrome(int x) {
if(x<0) return false;
if(x<10) return true;
if(x%10==0) return false;
int v =0;
while(x > v){
v = v*10;
v = v + x%10;
x = x/10;
}
if(v > x) v = v /10;
return v == x;
}
}