All,
I like palindromic* numbers. Today I thought of a problem that seems easy, but has me stumped for anything other than a brute force method.

Problem:
Given a base 10 number N, find the nearest palindromic base 10 number X to N. If N is already palindromic do nothing. If two palindromic numbers are equidistant to N, (10 - 1 = 9, 10 + 1 = 11) returning either is acceptable.

Here is my brute force implementation:

#!/usr/bin/perl use strict; use warnings; my $N = $ARGV[0] || 0; print nearest( $N ); sub nearest { my $N = shift; return $N if scalar(reverse $N) eq $N; my $pos = $N; ++$pos while scalar(reverse $pos) ne $pos; $pos = $pos - $N; my $neg = $N; --$neg while scalar(reverse $neg) ne $neg; $neg = $N - $neg; return $pos > $neg ? $N - $neg : $N + $pos; }

Challenge:
The primary goal is to solve the problem, as stated, using a technique other than the straight forward brute force method I presented. I am not personally interested in golfed solutions unless they satiate the primary goal, but feel free to add them either way to show off your talents. Additionally, having the ability to solve the problem in any base would get you bonus points.

* A palindromic number is one that is the same forwards and backwards such as 10701

Cheers - L~R


In reply to Challenge: Nearest Palindromic Number by Limbic~Region

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.