Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^3: Challenge: Nearest Palindromic Number

by tilly (Archbishop)
on Feb 03, 2005 at 07:15 UTC ( [id://427541]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Challenge: Nearest Palindromic Number
in thread Challenge: Nearest Palindromic Number

This works perfectly. :-)

For those who don't understand it, here's an explanation. Take the first half of the digits and build a palindrome. (Be careful, you need to keep it even/odd in size.) That palindrome is going to be larger or smaller than the original number. Adjust the first half up/down one then build a palindrome on the other side of the original number. One of those two is closest, so take the closer one.

To truly verify that it works (I'm just giving the handwaving explanation) you'll find that you actually are taking the nearest palindromes to either side in every case except where adding/subtracting from $first changes the number of digits that you have. But the only case where that happens is in 1 and numbers matching the pattern /^1(0*)(0|1)$/. In those cases $one winds up being 100...0001 and $two is wildly off. But in those cases, $one is one of the (possibly 2) acceptable answers, so the algorithm is right again.

  • Comment on Re^3: Challenge: Nearest Palindromic Number

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://427541]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-26 05:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found