问题定义
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?
判断一个数值反转之后是否还一样,包括符号在内要判断。
我的思路
这不和之前写的回文有点类似吗?所以我就先按回文的思路将数据进行逆向转换,可参考上一篇文章“Reverse Integer”
链接:https://blog.csdn.net/weixin_41775937/article/details/80304308
因为连符号都要判断,因此在两数相减时,我加上了绝对值,那么若是负数,即使转换后数值相等,但是相减也不为0啦。
开始这么写本来就有点懒惰的感觉,后面就想将integer类转换成string类进行回文判断,但是发现提示里面要求不要转成string类,大家知道还有这个方法就好啦。
代码
class Solution {
public boolean isPalindrome(int x) {
int reverse=0;
int xyuan=x;
while(x!=0){
reverse=reverse*10+x%10;
x=x/10;
}
return (Math.abs(reverse)-xyuan==0);
}
}
学习别人的代码
因为我自己的代码思路还是不行啊,效率低,但是我可以不断学习,让我们来学习一个名为cbmbbz的码友。
compare half of the digits in x, so don't need to deal with overflow.
public boolean isPalindrome(int x) {
if (x<0 || (x!=0 && x%10==0)) return false;
int rev = 0;
while (x>rev){
rev = rev*10 + x%10;
x = x/10;
}
return (x==rev || x==rev/10);
}
emmmmmm...好像差不多吼~不过因为他的判断,想法就比我写的多了,他的代码不用考虑溢出问题。