fork download
  1. '''
  2. Created on 17-Jul-2011
  3.  
  4. @author: Naresh
  5. '''
  6.  
  7. def nextPalindrome1(pal):
  8. length = len(pal)
  9. if (length & 1 == 0):
  10. if length == 0:
  11. return pal
  12. half = length >> 1
  13. if (needsIncrement(pal, half -1, half, length)):
  14. return increment(pal, half -1, half, length)
  15. else:
  16. return pal[0:half-1] + pal[half-1]*2 +(pal[0:half-1])[::-1]
  17. else:
  18. if length == 1:
  19. if (pal == "9"):
  20. return (11)
  21. else:
  22. return int(pal) + 1
  23. half = length >> 1
  24. if (needsIncrement(pal, half, half, length)):
  25. return increment(pal, half, half, length)
  26. else:
  27. return pal[0:half] + pal[half] +(pal[0:half])[::-1]
  28.  
  29. def increment(pal, i, j, length):
  30. if (length & 1 == 0):
  31. temp = pal[0:i] + pal[i]*2 +(pal[0:i])[::-1]
  32. else:
  33. temp = pal[0:i] + pal[i] +(pal[0:i])[::-1]
  34. intPal = int(pal)
  35. while (int(temp) <= intPal):
  36. index = i
  37. while(index >= 0):
  38. if (temp[index] != "9"):
  39. break;
  40. index -= 1
  41. if (index == -1):
  42. temp = "1" + ("0" * (j)) + temp[j:length]
  43. else:
  44. temp = temp[0:index] + `int(temp[index]) + 1` + (i - index)*"0" + temp[i+1:length]
  45. length = len(temp)
  46. half = length >> 1
  47. if (length & 1 == 0):
  48. temp = temp[0:half-1] + temp[half-1]*2 +(temp[0:half-1])[::-1]
  49. else:
  50. temp = temp[0:half] + temp[half] +(temp[0:half])[::-1]
  51. return temp
  52.  
  53. def needsIncrement(pal, i, j, length):
  54. tempI = i
  55. tempJ = j
  56.  
  57. while (i >= 0 and j < length):
  58. if (pal[i] < pal[j]):
  59. return True
  60. i-=1
  61. j+=1
  62.  
  63. while (tempI >= 0 and tempJ < length):
  64. if (pal[tempI] != pal[tempJ]):
  65. return False
  66. tempI -= 1
  67. tempJ +=1
  68.  
  69. if (tempI == -1 and tempJ == length):
  70. return True
  71. return False
  72. import sys
  73. import gc
  74. import psyco
  75. if __name__ == '__main__':
  76. strip = str.strip
  77. gc.disable()
  78. psyco.full()
  79. data = sys.stdin.readlines()
  80. for i in range(1, len(data)):
  81. input = strip(data[i])
  82. length = len(input)
  83. j = 0
  84. while (j < length):
  85. if (input[j] != '0'):
  86. break
  87. else:
  88. j+=1
  89. str = input[j:length]
  90. if (len(str) == 0 and len(input) > 0):
  91. print "1"
  92. else:
  93. print nextPalindrome1(str)
  94.  
Runtime error #stdin #stdout 0.02s 5852KB
stdin
1234
stdout
Standard output is empty