判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/palindrome-number 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution { // C++
public:
bool isPalindrome(int x) {
if(x < 0 || x%10 == 0 && x != 0)
return false;
long reverse = 0;
int pos, copy = x;
while(copy)
{
pos = copy%10;
copy /= 10;
reverse = reverse*10 + pos;
}
return reverse == x;
}
};
or 转字符串处理
class Solution { //c++
public:
bool isPalindrome(int x) {
string s1 = to_string(x);
string s2 = s1;
reverse(s2.begin(),s2.end());
return s1==s2;
}
};
class Solution:# py3
def isPalindrome(self, x: int) -> bool:
a = str(x)
return "".join(reversed(a))==a
or
class Solution:# py3
def isPalindrome(self, x: int) -> bool:
a = str(x)
return a[::-1]==a