196 algorithm code golf
Python 2, 55 bytes
Following JPvdMerwe suggestion:
n=input()
while`n`!=`n`[::-1]:n+=int(`n`[::-1])
print n
Python 2, 62:
n=raw_input()
while n!=n[::-1]:n=`int(n)+int(n[::-1])`
print n
GolfScript, 29 chars
~]{{.`.-1%.@={;0}{~+1}if}do}%
Selected commentary
The meat of the program is the do
loop, of course. So I'll just cover that.
.`
copies the number and stringifies it..-1%
copies that string version and reverses it..@
copies the reversed version, and brings the original non-reversed version to the front.
So, say, the number is 5280. At this stage, the stack is: 5280 "0825" "0825" "5280"
. The stage is set for the comparison. (After the comparison, the stack will be left at 5280 "0825"
no matter what---the items to compare have been popped off.)
- If the string and the reverse are the same, we don't care about the reversed string, so just pop it off (
;
) and return 0 (to end thedo
loop). - If they don't match, then evaluate (
~
) the reversed string (to make it a number), add (+
) that to the original number, and return 1 (to continue thedo
loop).
APL (22 characters)
{a≡⌽a←⍕(⍎⍵)+⍎⌽⍵:a⋄∇a}⍞
This works in Dyalog APL. Here's an explanation, from right to left:
{ ... }⍞
: Get input from the user as characters (⍞
) and feed it to our function ({ ... }
).- Within the direct function (
⋄
separates statements, so we look at them from left to right):a≡⌽a←⍕(⍎⍵)+⍎⌽⍵ : a
: Evaluate (⍎
) the right argument's (⍵
) reverse (⌽
), and add that to the evaluated version of the right argument itself. Then, format the result (⍕
; i.e., give its character representation), assign (←
) that to the variablea
, and finally test ifa
's reverse is equivalent toa
(i.e., isa
a palindrome?). If true, returna
; otherwise...∇a
: Feeda
back into our function (∇
is implicit self-reference).
Example:
{a≡⌽a←⍕(⍎⍵)+⍎⌽⍵:a⋄∇a}⍞
412371
585585