Sunday, February 3, 2013

[Yahoo] Cloest palindrome number, Solution

Given an integer, print the closest number to it that is a palindrome - eg, the number "1224" would return "1221".

[Thoughts]

pseudo code: (with two examples in parentheses)

- Convert the number into string. (1224, 39999)
- take half of the string. ( "12", "399" )
- copy first half to second half in reverse order (take care of no of chars) ( "12" -> "1221", "399" -> "39993" )
- convert to number and measure the abs. difference with original number - diff1 ( |1221 - 1224| = 3, |39993-39999| = 6)
- add 1 to half string and now copy first half to second half in reverse order ( 12+1 = 13, 399 + 1 = 400, 13-> 1331, 400->40004)
- convert to number and measure the abs. difference with original number - diff2 ( |1331-1224| = 107, |40004-39999| = 5 )
- if diff1<diff2 return first number else return second number ( 1221, 40004)

No comments:

Post a Comment