http://qs321.pair.com?node_id=427378

Limbic~Region has asked for the wisdom of the Perl Monks concerning the following question:

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