题目描述
Given an integer x, return true if x is a palindrome, and false otherwise.
给你一个整数 x ,如果 x 是一个回文整数,返回 true;否则,返回 false。 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 例如,121 是回文,而 123 不是。
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.
来源:力扣(LeetCode)
题目解析
将给定的整数翻转,再与原数字比较是否相同。注意:为了避免整型溢出,只翻转一半长度。
解题方法
方案一:翻转一半长度的给定整数
可以使用 x % 10 来获取给定数字的最后一位,比如 1221 % 10 = 1 就取到最后一位的数字1,接着再取倒数第二位的数字 122 % 10 = 2,此时,翻转后的数字就是 1 * 10 + 2 = 12。在此过程中,给定的整数x会越来越小,翻转后的整数会越来越大,当给定整数大于翻转后的整数时,都需要继续翻转。
C#:
public class Solution {
public bool IsPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int re = 0;
while (x > re) {
re = re * 10 + x % 10;
x /= 10;
}
return x == re || x == re / 10;
}
}
Java:
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int rev = 0;
while (x > rev) {
rev = rev * 10 + x % 10;
x /= 10;
}
return x == rev || x == rev / 10;
}
}
Python:
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (x % 10 == 0 and x != 0):
return False
rev = 0
while x > rev:
rev = rev * 10 + x % 10
x /= 10
return x == rev or x == rev / 10
复杂度分析
- 时间复杂度:O(log10(n)). We divided the input by 10 for every iteration, so the time complexity is O(log10(n)).
- 空间复杂度:O(1).