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.
Cheers - L~R
In reply to Challenge: Nearest Palindromic Number by Limbic~Region
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |