SPOJ Next Palindrome:无法弄清楚我的代码获得TLE的时间(超出时间限制)

时间:2017-04-19 07:10:33

标签: python palindrome

下面提到的是我的Python代码,它打印出比K更小的最小回文,对于给定的输入K(K可以有10 ^ 6位数)。可能不是最好的算法,但它有效,我尝试使用最少量的资源。也没有太多的循环涉及(除非所有9'的情况)。无论如何,我的代码正在获得TLE(时间限制超过),我不知道为什么。任何人都可以通过指出它可能会变得太滞后来帮助我吗?谢谢!

以下代码:

def palin(num):
    if int(num) < 9 or int(num)%10 == 0:
        return int(num) + 1
    if int(num) == 9:
        return 11
    if int(num) >= 90 and int(num) < 99:
        return 99
    numList = []
    if len(num)%2 == 0:
        numList = list(num[:len(num)/2])
    else:
        numList = list(num[:(len(num)/2 + 1)])
    flag = 0
    carryOver = 1
    sum = 0
    i = len(numList) - 1
    while i >= 0:
        sum = (int(numList[i]) + carryOver)
        numList[i] = sum % 10
        carryOver = sum / 10
        if carryOver > 0: 
            i -= 1
        else:
            break
    if i < 0 and carryOver > 0:
            numList.insert(0,carryOver)
            flag = 1
    s = ''.join(map(str,numList))
    if flag == 1:
            if len(num)%2 == 0:
                temp = s[:-1]
                temp = temp[::-1]
                s = s[:-1] + s[-1:] + temp
                return int(s)
            else:
                temp = s[:-2]
                temp = temp[::-1]
                s = s[:-2] + s[-2:] + temp
                return int(s)
    else:
            if len(num)%2 == 0:
                temp = s[::-1]
                s = s + temp
                return int(s)
            else:
                temp = s[:-1]
                temp = temp[::-1]
                s = s[:-1] + s[-1:] + temp
                return int(s)

if __name__ == '__main__':
    t = raw_input()
    numList = []
    for i in range(int(t)):
        numList.append(raw_input())
    for i in range(int(t)):
        print palin(numList[i])

0 个答案:

没有答案