9. Number of palindrome
Determine whether an integer is a palindrome. The palindrome number refers to the same integer in both positive order (from left to right) and reverse order (from right to left).
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: Reading from left to right, it is -121. Reading from right to left, it is 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reading from right to left, it is 01. Therefore it is not a palindrome.
Problem-solving ideas
Odd number:
even number:
Code
class Solution {
public boolean isPalindrome(int x) {
//负数直接不是回文
if(x <0){
return false;
}
//将数字的每一位存入list
ArrayList<Integer> list = new ArrayList();
int temp =0;
while(x!=0){
temp = x%10;
x = x/10;
list.add(temp);
}
boolean flag =true;
//将list转成Integer[]
Integer[] integers = list.toArray(new Integer[list.size()]);
//遍历,条件的=号是为了解决偶数个的比较问题
for(int i=0, j=integers.length-1; i<=integers.length/2 && j>=integers.length/2; i++,j--){
//判断
if(integers[i] != integers[j]){
flag = false;
}
}
return flag;
}
}