Palindrome
首先,先贴出代码:
class Solution {
public boolean isPalindrome(int x) {
long res = 0;//(1)
int cx = x;//(2)
if(x<0){//(3)
return false;
}
while(x!=0){ //(4)
res = res*10+x%10;
x = x/10;
if(res>Integer.MAX_VALUE||res<Integer.MIN_VALUE){ //(5)
return false;
}
}
return (int)res==cx;
}
}
简介:本题是让判断一个整数是否具有首尾回环性质,一个整数反过来还是本身
解题思路:
在给出的示例中,第二个例子是-121,数字反过来是121-,虽然数字部分仍是本身,但是前边的“-”翻转到后面了,所以从这个例子得出一个条件:所有的负整数输入,都应当输出false(如标注(3)中代码所示)。
接下来的重点就是求出正整数反过来之后的数字,然后比较反过来的数字是否与输入数字相等。
在这里应当注意,输入的数字类型是int型,因此反过来之后范围可能会超出int的长度,所以反过来的值应当用比int型范围大的long型来存储(如标注(1)代码所示)。
对输入的整数从右到左依次通过“%”运算符得出每个数位的数字,然后通过“/”运算符得出去除该数字剩下的整数,一直到剩下的数字为0,说明循环到最右边了,此时res保存的就是反过来的整数,然后与之前的输入值进行比较得出结果,这里使用一个变量cx(如标注(2)所示)保存原始值,因为在循环最后x的值已经变为0了,同时标注(5)的代码是判断当前res是否超出了int类型的范围,如果超出了直接返回false,不需要接下来的循环了。