如何在0.5秒内从L到R
(1 <= L <= R <= 10^12)
统计有多少个总位数能被10整除的回文数?
我的想法:生成回文数然后计数。但它是 TLE。
这是我的代码:
def circle_num(x):
t = 0
for digit in str(x):
t += int(digit)
if t % 10 == 0:
return True
else:
return False
def palinstr_evendig(half):
return half + half[::-1]
def palinstr_odddig(h):
return h + (h[::-1])[1:]
def num_palin_circle_num_1to(t, k):
r = 0; j = 1
while not int(palinstr_odddig(str(j))) > k:
a = int(palinstr_evendig(str(j)))
if (not a > k) and (not a < t) and (circle_num(a)):
r += 1
b = int(palinstr_odddig(str(j)))
if (not b > k) and (not b < t) and (circle_num(b)):
r += 1
j += 1
return r
s = input()
l, r = map(int, s.split())
print(num_palin_circle_num_1to(l, r))
我没有任何想法可以实施。 Python 语言
有人可以帮助我吗?非常感谢。
我假设你正在计算回文数 L ≤ x < R. If R is inclusive, just replace R with R + 1 below.
假设我们有一个函数 f(N),它可以计算符合您的标准的回文数,使得 0 ≤ x < N. Then we'd just need to calculate F(R) - F(L). [Or f(R + 1) - f(L) is R is inclusive].
那么让我们看看偶回文和奇回文。
假设我们想要找到 f(314159)。
因此,您可以在与 n 中的位数成线性关系的时间内计算 f(n)。
实现这一点并不难。我假设您正在尝试计算 f(N),其中 N 是一个 n 位数字。 N < 100 is trivial (is 0 < N? is 55 < N?), so I'm going to assume n≥3.
的情况有多少个长度为 m 的 10 回文,其中 1 ≤ m < n?
有多少个长度为 n 且小于 N 的 10 回文? 对于长度n。假设如果 n 为奇数,则 N 为 AB...DED...BA;如果 n 为偶数,则 N 为 AB...DEED...BA。
这大约有二十行代码。