版权声明:本文为博主原创文章,转载请注明原博客地址 https://blog.csdn.net/qunqunstyle99/article/details/88141683
Palindrome Number
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?
题目分析
判断回文数,就是正序和反序是一样的数字,负数不是回文数。
原来做的思路是就是用的字符串,然后翻转字符串,与原来的进行比较,比较费事费时。
这里还提示了看是否可以不使用String来解决这个问题。
因为输入是一个int型的数,不考虑超出int型边界。
采用依次对10取余获得最低位,然后除以10删掉最低位。依次操作指导等于零,然后加回来判断是否一致。
class Solution {
public boolean isPalindrome(int x) {
final int origin = x;
if(x<0) return false; //负数一定不是回文
ArrayList<Integer> array = new ArrayList<>(); //保存每个位的数字
do{
int tmp = x % 10;
array.add(tmp);
x = x / 10;
}while(x>0);
//再把这个数字翻转成int
int reversed = array.get(0);
int len = array.size();
for(int i=1;i<len;i++){
reversed = 10*reversed + array.get(i); //累加
}
return reversed==origin;
}
}