zl程序教程

您现在的位置是:首页 >  其他

当前栏目

LeetCode 9. 回文数

LeetCode 回文
2023-06-13 09:13:26 时间

文章目录

1. 题目信息

判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例 1:

输入: 121
输出: true
示例 2:

输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:

输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/palindrome-number 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

  • 先排除负数,后缀是0的数(除开0)
  • 分别取出个位、十位。。。乘以10,乘以10,得到反向数的值
  • 比较反向数与原数(注意可能溢出)
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