每天一题LeetCode[第七天]
Palindrome Number
Description:
Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
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.
Subscribe to see which companies asked this question.
Show Tags
Show Similar Problems
解题过程:
- 一开始被Do this without extra space 疑惑到了。。。是指不允许再开任何一个变量么?然后偷偷了大概扫了一眼Top Solution,貌似多了一个int rev,然后哦,我也限制自己用一个int变量吧。然后,在想一个大概思路,最后想到了,前后拼接。。我傻啊,既然如果可以得到前后,那判定两个是否相等(注意分情况,奇数,偶数)
Java代码:
public class Solution {
private static final String TAG=Solution.class.getSimpleName();
public boolean isPalindrome(int x){
//负数,以及尾数为0的正数都是不行的
if(x<0 || (x!=0 && x%10==0)){
return false;
}
int rev=0;
while (x>rev){
rev=rev*10+x%10;
x/=10;
}
return (rev==x || x==rev/10);
}
}
提高代码质量就是:积累精美的代码,优质的细节的过程。