【LeetCode】 9. Palindrome Number 回文数(Easy)(JAVA)
题目地址: https://leetcode.com/problems/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?
题目大意
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
解题方法
1、负数不是回文数
2、对 x 进行反转,然后比较是否相同就行;只需要反转一半即可
note: 注意以 0 结尾的,除了 0 都不是回文数
class Solution {
public boolean isPalindrome(int x) {
if (x >= 0 && x <= 9) return true;
if (x < 0 || x % 10 == 0) return false;
int res = 0;
while (res < x) {
res = res * 10 + x % 10;
x /= 10;
}
return res > x ? (res / 10 == x) : (res == x);
}
}
执行用时 : 9 ms, 在所有 Java 提交中击败了 98.69% 的用户
内存消耗 : 39.9 MB, 在所有 Java 提交中击败了 5.02% 的用户