Here is the question:
A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.
Input: The first line contains integer t, the number of test cases. Integers K are given in the next t lines.
Output: For each K, output the smallest palindrome larger than K. Example
Input:
2 808 2133
Output:
818 2222
And my Scala
code:
object Pro_5 {
// find the next palindrome larger than K
def findPalindrome(input: String) = {
// start from (k + 1)
val tmp = (BigInt(input) + 1).toString
val length = tmp.length
val mid = length / 2
val left = tmp.substring(0, length >> 1)
val right = tmp.substring(length >> 1, length)
// whether continue for loop
var flag = true
// half of the result
var res = ""
for (i <- 0 until mid if flag) {
if (left(i) > right(mid - 1)) {
res = left
flag = false
} else if (left(i) < right(mid - 1)) {
res = (BigInt(left) + 1).toString()
flag = false
}
}
if (length % 2 == 0) {
res + res.reverse
} else {
res + tmp(mid) + res.reverse
}
}
// get K
def getInput(times: Int) = {
for (time <- 0 until times) yield readLine()
}
def main(args: Array[String]) {
// get compute times
val times = readInt()
getInput(times).map(findPalindrome(_)).foreach(println)
}
}
I learn something from Mark Peters
's answer
But when I run it in the SPOJ
, i still got a time limit exceeding error.
Can you help me to improve the algorithm?
Any answer will be welcom...