[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)
[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)
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步