Make a number palindrome
Perl, 32 chars
s/((.)(?1)\2|.?)$/$&.reverse$`/e
Needs Perl 5.10 or later for regex features, but no special command-line switch.
Sample use:
$ perl -pe 's/((.)(?1)\2|.?)$/$&.reverse$`/e' << EOT
> 12
> 232
> 2323
> 1012121
> EOT
121
232
23232
101212101
Uses Perl 5.10's recursive regex extensions to match the longest trailing palindrome as such:
m/
( # paren 1 - a palindrome is either:
(.) # paren 2 - a character
(?1) # a palindrome as defined in paren 1
\2 # the same character as in paren 2
| # or:
.? # a 0- or 1-character string
)
$ # at end of string
/x
It then replaces it with itself ($&
) and appends whatever the string started with ($`
), reversed.
Brachylog 2, 8 bytes, language postdates challenge
ẹ;AcB↔Bc
Try it online! The question asks for a function, so I provided one; the TIO link takes an argument that runs a function like a full program.
Explanation
ẹ;AcB↔Bc
ẹ Split {the input} into digits
;Ac Append {the shortest possible} list
B↔B to produce a palindrome
c then concatenate the resulting list of digits back into a number
J, 50, 32 26 characters!
f=:{.@(,"1(-:|.)\.#|.@}:\)
eg
f '12'
121
f '232'
232
f '2323'
23232
f '1012121'
101212101
How it works (by example)
y =: '1012121'
[\.y NB. Sub lists of y
1012121
012121
12121
2121
121
21
1
|.\. y NB> Reverses of sub lists of y
1212101
121210
12121
1212
121
12
1
([\. y) -:"1 (|. \. y) NB. Which of them are equal? (those are palindromes)
NB. ( -:"1 ) checks equality item by item
0 0 1 0 1 0 1
(-: |.)\. y NB. Shortcut of the above
0 0 1 0 1 0 1
(0 0 1 0 1 0 1) # }:\y NB. Choose (#) the palindrome prefixes (\)
10
1012
101212
y, |.'10' NB. Reverse and append the first prefix.
101212101