题目描述
题目链接:9. Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
例子
例子 1
Input: 121 Output: true
例子 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.
例子 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?
解题思路
首先如果不是正数可以直接返回结果(负数为 false
,0 为 true
),正数的情况通过求余从个位开始赋值到另一个整型最后判断两数是否相等即可。注意由于翻转的时候 int
可能放不下,所以存翻转值的类型需要是 long
。代码如下:
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
if (x == 9) return true;
long x1 = 0;
int copy = x;
while (x > 0) {
x1 *= 10;
x1 += x % 10;
x /= 10;
}
return x1 == copy;
}
};
- 时间复杂度: O(digits of
x
) - 空间复杂度: O(1)
GitHub 代码同步地址: 9.PalindromeNumber.cpp
其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions