leetcode 腾讯精选练习(50 题)6.回文数

原题目

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 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.

Example 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?

思路
  1. 将整数转换为字符串判断是否是回文数
  2. 首先对整数取绝对值,然后进行取余除10的操作得到其回文数字,比较原数字和回文数字是否相等判断是否是回文数
第一遍解法
# Runtime: 68 ms, faster than 98.32% of Python3
# Memory Usage: 13.3 MB, less than 55.67% of Python3
class Solution:
    def isPalindrome(self, x):
        x = str(x)
        return x == x[::-1]
# Runtime: 76 ms, faster than 96.82% of Python3 
# Memory Usage: 13.2 MB, less than 60.70% of Python3
class Solution:
    def isPalindrome(self, x):
        reverse = 0
        x_copy = x
        while x != 0:
            reverse = reverse * 10 + x % 10
            x = x // 10
        return x_copy == reverse
网上好的解法
class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0|| (x!=0 &&x%10==0)) return false;  //负号 或 x不为0且最后一位为0 返回 false
        int sum=0;
        while(x>sum) //测试一半就能知道结果
        {
            sum = sum*10+x%10;
            x = x/10;
        }
        return (x==sum)||(x==sum/10);  //偶数位回文相等,奇数位回文等于 sum/10
    }
};
自己可以改进的地方
  1. 提前筛选,负数和余数为 0 的数(不包括 0)直接返回 false,不用之后的判断,减少机器计算量
  2. 测试一半比较两个数而不用全部转换完再比较,既能节省空间也能节省时间
最简代码
class Solution:
    def isPalindrome(self, x):
        if x < 0 or (x != 0 and x % 10 == 0):
            return False
        reverse = 0
        while x > reverse:
            reverse = reverse * 10 + x % 10
            x = x // 10
        return x == reverse or x == reverse // 10
获得的思考

如果能提前将不符合的数据剔除应该有限考虑剔除,从而节省计算资源,提升算法的效率。但是好的算法需要深入的思考才能获得好的时间空间复杂度。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值