LeetCode 9. Palindrome Number (Easy)
题目
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is a palindrome while 123 is not.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -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: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
思路
解法(Java):
由于题目建议不要将x转为字符串处理,这里我们使用一个int变量reverse来记录x从末尾向前翻转过来的数,循环终止条件x > reverse存在两种情况,
x = reverse 两者位数相同(原x表示的数的位数为偶数)
x < reverse reverse位数比x多一位(原x表示的数的位数为奇数)
class Solution {
public boolean isPalindrome(int x) {
// 负数,不为0但以0结尾的数
if(x < 0 || (x % 10 == 0 && x != 0)) return false;
int reverse = 0;
while(x > reverse){
reverse = reverse * 10 + x % 10;
x /= 10;
}
// 偶数位 和 奇数位情况
return x == reverse || x == reverse / 10;
}
}

浙公网安备 33010602011771号