基础练习 特殊回文数 python

基础练习 特殊回文数 python

在这里插入图片描述
在做这道题时,我的代码(注释部分)一直超时。后来我算了一下我的时间复杂度,虽然我只用了一层循环,也就是O(n),但是它循环了1000000-10001=989999次。后来我突然想到它是回文数,最大也就六位还是两边对称的情况,我可以把每一位拆开看每一位可能的数字只有10个,排列前半部分即使有三层循环,但也只需要循环1000次,这样就大大减少了时间。
代码如下:

# import datetime
# start = datetime.datetime.now()

# n = eval(input())
# for i in range(10001, 1000000):
#     a = i // 100000
#     b = (i // 10000) % 10
#     c = (i // 1000) % 10
#     d = (i // 100) % 10
#     e = (i // 10) % 10
#     f = i % 10
#     sum = a + b + c + d + e + f
#     if a == 0:
#         if b != f or c != e:
#             continue
#     else:
#         if a != f or b != e or c != d:
#             continue
#     if sum == n:
#         print(i)

# end = datetime.datetime.now()
# print (end-start)

n = eval(input())

if n % 2 == 1:
    for a in range(1, 10):
        for b in range(10):
            for c in range(10):
                if (a + b) * 2 + c == n:
                    res = str(a) + str(b) + str(c)
                    print(res + res[1::-1])
else:
    for a in range(1, 10):
        for b in range(10):
            for c in range(10):
                if (a + b) * 2 + c == n:
                    res = str(a) + str(b) + str(c)
                    print(res + res[1::-1])
    for a in range(1, 10):
        for b in range(10):
            for c in range(10):
                if (a + b + c) * 2 == n:
                    res = str(a) + str(b) + str(c)
                    print(res + res[::-1])

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值