[Question]
  [
Write a short program for [196-algorithm](http://mathworld.wolfram.com/196-Algorithm.html).
The algorithm starts from an integer, then adds its reverse to it until a palindrome is reached.
e.g.
```
input = 5280
5280 + 0825 = 6105
6105 + 5016 = 11121
11121 + 12111 = 23232
output = 23232
```
**Input**
an integer, which is not a [lyrchrel number](https://en.wikipedia.org/wiki/Lychrel_number) (that is, it does eventually yield a palindrome under this algorithm, rather than continuing infinitely)
**Output**
the palindrome reached.
  
[Answer]
## 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 variable `a`, and finally test if `a`'s reverse is equivalent to `a` (i.e., is `a` a palindrome?). If true, return `a`; otherwise...
	+ `∇a`: Feed `a` back into our function (`∇` is implicit self-reference).
Example:
```
      {a≡⌽a←⍕(⍎⍵)+⍎⌽⍵:a⋄∇a}⍞
412371
585585
```
[Answer]
## 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.
1. `.`` copies the number and stringifies it.
2. `.-1%` copies that string version and reverses it.
3. `.@` 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.)
1. 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 the `do` loop).
2. 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 the `do` loop).
[Answer]
# 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
```
[Answer]
**Ruby — 56 chars**
```
x,r=gets
x="#{x.to_i+r.to_i}"until x==r=x.reverse
puts x
```
[Answer]
Just exercising my Pyth skills, not a serious contender.
# Pyth, 16 bytes
```
L?bqb_by`+vbi_bTyz
```
Equivalent to Python 3:
```
y=lambda b:b if b==b[::-1] else y(str(eval(b)+int(b[::-1],10)))
print y(input())
```
[Answer]
# J 25 27 31
```
f=:(+g)^:(~:g=.|.&.":)^:_
e.g.
f 5280
23232
```
[Answer]
# CJam, ~~22~~ 21 bytes
CJam was created after this question was asked, so technically its an invalid submission. But I found the question interesting, so here goes:
```
r{__W%:X=0{~X~+s1}?}g
```
Explanation:
```
r{                 }g    "Read the input number as string and enter a while-do loop";
  __                     "Make 2 copies of the string number";
    W%:X                 "Reverse the second and store it in X";
        =                "Check if the number is already palindrome";
         0{      }?      "Put 0 on stack if it is palindrome, else, run the code block";
           ~             "Convert the string to int";
            X~           "Put the reverse string on stack and convert it to int too";
              +s         "Add the two numbers and covert back the result to string";
```
The core logic is that in each while-do iteration, you first check if palindrome is achieved or not. If not, add the reverse to the number. Pretty much what the algorithm is!
[Try it online here](http://cjam.aditsu.net/)
[Answer]
This is an actual contender, since J has been around for decades.
# J (16 bytes)
```
(+^:~:|.&.":)^:_
```
This is a verb, so it can be assigned to a variable in a J session and used like so:
```
   f =. (+^:~:|.&.":)^:_
   f 5280
23232
```
How it works:
```
(+^:~:|.&.":)^:_
 +^:~:           add if unequal
      |.&.":     reverse under string format
 +^:~:|.&.":     add reverse unless a palindrome
(           )^:_ repeat until unchanged
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 7 bytes
Code:
```
[DÂQ#Â+
```
Explanation:
```
[        # Infinite loop.
 DÂ      # Duplicate and bifurcate (which duplicates it and reverses the duplicate).
   Q#    # If the number and the number reversed are equal, break.
     Â+  # Add the reversed number to the initial number.
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=W0TDglEjw4Ir&input=NTI4MA).
[Answer]
Python: 66
```
n=input()
while 1:
 r=int(`n`[::-1])
 if n==r:break
 n+=r
print n
```
[Answer]
Perl, 40 chars
```
$_=<>;$_+=$r while$_!=($r=reverse);print
```
[Answer]
# PHP - ~~54~~ 48 characters
```
<?for($s=`cat`;$s!=$r=strrev($s);$s+=$r);echo$s;
```
Test:
```
$ php 196.php <<< 5280
23232
```
[Answer]
### Scala 82
```
def p(n:Int):Int={val s=n.toString.reverse.toInt
if(n==s)n else p(n+s)}
p(readInt)
```
[Answer]
# [JAGL](http://github.com/globby/jagl) Alpha 1.2 - 19, 21 with stdin
***Not contending***, just getting some experience with my language  
Expects a number from stdin
```
T~d{DddgCi+dgdC=n}uSP
```
Explanation
```
T~                       Get a line of input, and eval to an integer
  d                      Duplicate (for first round)
   {Ddd                  Drop last and duplicate twice
       gCi               Convert to string, reverse, and convert back to integer
          +d             Add to original and duplicate
            gdC          Convert to string, duplicate, reverse
               =n}       If it isn't a palindrome, keep going
                  uSP    Run until palindrome reached, then print output number
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
↔?|↔;?+↰
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HbFPsaIGFtr/2obcP//6ZGFgb/owA "Brachylog – Try It Online")
Somewhat similar to one of the first Brachylog programs I saw and was intrigued by, from the [Brachylog introduction video](https://youtube.com/watch?v=XYVhZ-MFcUs). 
```
?↔?.|↔;?+↰.  (initial ? and the .s are implicit)
?↔?          % If the input and its reverse are the same,
   .         %   then the input is the output
    |↔;?+↰   % Or, add the input and its reverse, and call this predicate recursively
          .  % The result of that is the output
```
[Answer]
## Bash (64)
```
X=`rev<<<$1|sed s/^0*//`;[ $1 = $X ]&&echo $1||. $0 $(($1+$X))
```
Call with: bash <filename> <number>
[Answer]
## C# - 103 99 chars
```
public int P(int i)
{
    var r = int.Parse(new string(i.ToString().Reverse().ToArray())));
    return r == i ? i : P(i + r);        
}
```
C# never does very well in golf. Elegant, but verbose.
[Answer]
## In Q (39 characters)
```
f:{while[x<>g:"I"$reverse -3!x;x+:g];x}
```
Sample Usage:
```
q)f 5280
23232
```
Edit:
Down to 34 now, same usage:
```
{while[x<>g:"I"$(|) -3!x;x+:g];x} 5280
```
[Answer]
```
r=input()
while 1:
    r=`r`
    if r==r[::-1]:
      break
    else:
      r=int(r)+int(r[::-1])
print r
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes (non competing)
A very simple answer, just for the challenge of coding in and esoteric language.
`ṚḌ+µŒḂ¬$¿`
```
ṚḌ        : take the argument, reverse (and vectorize) it
  +µ      : add both
    ŒḂ¬$¿ : while the result isn't a palindrome
```
[Try it online!](https://tio.run/##ASEA3v9qZWxsef//4bma4biMK8K1xZLhuILCrCTCv////zUyODA "Jelly – Try It Online")
Should this answer be unclear or wrong on any level, feel free to point it out.
Thanks to Dennis for helping me out with this first small piece of code.
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~78~~ 71 bytes
```
i->{for(int r=0,t;i!=r;)for(t=i+=r,r=0;t>0;t/=10)r=r*10+t%10;return i;}
```
[Try it online!](https://tio.run/##NY6xasNADIZn31OoQ8HXJO45UAgcF5qlkKFTxtJBdeygxDkHnWwowc/uyqUVSKCPn5/vjAOuzsfLVLWYErwjRbib17c@VkJdxHYfpeYGq9pkN6YBpQb6R7DXbJbpD00@X7TeZKM3BnSSoFClmR2EiVbbe9Pxb4qDW4qnh8DezkwCLQIvFXvZ6j6H0lkO/FS6hTyWznMtPUcgP07e3PqvVmv/2oeOjnBV6/wgTPH08QnIp2RVbHY4fCepr0XXS6H2UdqY74omf1lvnFVXgNGM0w8 "Java (JDK) – Try It Online")
-7 Thanks to Celingcat!
[Answer]
Python. 85 characters:
```
s,i=str,int;rs=lambda q:s(q)[::-1];n=i(input());
while rs(n)!=s(n):n+=i(rs(n));print n
```
If you don't want output on each iteration:
```
s,i=str,int;rs=lambda q:s(q)[::-1];n=i(input());
while rs(n)!=s(n):n+=i(rs(n))
print n
```
(one less character)
[Answer]
### Windows PowerShell (63)
```
for($a=+"$input";-join"$a"[99..0]-ne$a){$a+=-join"$a"[99..0]}$a
```
I still hate it that there is no easy way to reverse a string.
[Answer]
**Haskell ~~89~~ 87 chars**
```
r=read.reverse.show
main=getLine>>=print.head.filter(\x->x==r x).iterate(\x->x+r x).read
```
Somewhat readable version:
```
myFind p = head . filter p
rev = read . reverse . show
isPalindrome x = x == rev x
next x = x + rev x
sequence196 = iterate next
palindrome196 = myFind isPalindrome . sequence196
main = getLine >>= print . palindrome196 . read
```
The golfed version was created by manual inlining and renaming the remaining functions to single character names.
[Answer]
## befunge, 57 bytes
```
"KCTS"4(&:0\v
\T\a*+\:0`jv>:a%\a/
0:+_v#-TD2$<^\
  @.<
```
though the code is places in a 4x19 grid, so might call it 76.
* first line is initializeing, and reading input number
* second line reverse first number in stack and put it in the second stack position.
* and the third line checks if a number is palindrome.
[Answer]
## C++ TMP (256 characters)
```
#include<cstdio>
#define Y(A,B,C,D)template<int N>struct A<C,D>{enum{v=B};};
#define Z(A)template<int N,int M>struct A{enum{v=
#define n 5194
Z(R)R<N/10,M*10+N%10>::v};};Y(R,N,0,N)Z(S)S<N+M,R<N+M,0>::v>::v};};Y(S,N,N,N)main(){printf("%d",S<n+R<n,0>::v,0>::v);}
```
This version could be shortened a bit, but a 256-character answer is hard to pass up. Here's an un-golfed version:
```
#include <iostream>
template<size_t N>
class Reverse
{
    template<size_t M, size_t R>
    struct Inner
    {
        enum { value = Inner<M/10, R*10 + M%10>::value };
    };
    template<size_t R>
    struct Inner<0, R>
    {
        enum { value = R };
    };
public:
    enum { value = Inner<N, 0>::value };
};
template<size_t N>
class OneNineSix
{
    template<size_t M, size_t R=Reverse<M>::value>
    struct Inner
    {
        enum { value = OneNineSix<M + R>::value };
    };
    template<size_t M>
    struct Inner<M, M>
    {
        enum { value = M };
    };
public:
    enum { value = Inner<N + Reverse<N>::value>::value };
};
int main()
{
    const size_t N = 4123;
    std::cout << OneNineSix<N>::value << std::endl;
}
```
[Answer]
## Pyke, 13 bytes (noncompeting)
```
D`_b]D$XIsr)h
```
[Try it here!](http://pyke.catbus.co.uk/?code=D%60_b%5DD%24XIsr%29h&input=89&warnings=0)
```
 `_b          -     int(reversed(str(num))
D   ]         -    [num, ^]
     D        -   _ = ^
      $       -  delta(^)
       XI     - if ^:
         s    -  num = sum(_)
          r   -  goto_start()
            h - _[0]
```
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 57 bytes
```
L,BDbRBv
D,f,@,1]A+
D,g,@,1]A=
D,h,@,{f}A{g}Q{h}
L,{h}2/i
```
[Try it online!](https://tio.run/##S0xJKSj4/99Hx8klKcipjMtFJ03HQccw1lEbyEyHMG2BzAwgszqt1rE6vTawOqOWy0cHSBrpZ/5XyUnMTUpJVDCys@fy///f1MjCAAA "Add++ – Try It Online")
## How it works
```
L,	; Create a function 'lambda 1'
	; Example argument:   [5280]
    BD	; Digits;     STACK = [[5 2 8 0]]
    bR	; Reverse;    STACK = [[0 8 2 5]]
    Bv	; Undigits;   STACK = [825]
D,f,@,	; Define a monadic function 'f'
	; Example argument:         [5280]
    1]	; Call 'lambda 1';  STACK = [825]
    A+	; Add the argument; STACK = [6105]
D,g,@,	; Define a monadic function 'g'
	; Example argument:          [5280]
    1]	; Call 'lambda 1';   STACK = [825]
    A=	; Equal to argument; STACK = [0]
D,h,@,	; Define a monadic function 'h'
	; Example argument:  [5280]
   {f}	; Call 'f';  STACK = [6105]
   A{g}	; If 'g'...
   Q	;   Return
   {h}	; Else call 'h'
L,	; Define a function, 'lambda 2'
	; Example argument: [5280]
   {h}	; Call 'h'; STACK = [46464]
   2/i	; Halve;    STACK = [23232]
```
[Answer]
# C (gcc), 132 bytes
```
t;r(char*s){char*e=s+strlen(s)-1;for(;e>s;*e--=*s,*s++=t)t=*e;}g(o,l,f){for(l=malloc(9);sprintf(l,"%d",o),r(l),f=atoi(l),f-o;)o+=f;}
```
Call with `g(n)` for an `int n`. Try it online [here](https://tio.run/##bYvLCsIwFETX@hWlIOTmAdoqKJf4JW5CTGohTSTJrvTbY1pcllnMwDmjxaB1KRkj0R8VaYJ5ayMTSzk640kCcUEbIkHzTEiNEJImThNjMkOW1OAykMAdtzCvmpOTci5o8gBM3zj6bInj7end8gC8cuBWqhzGbYmAEJi0uJRqNpMaPYFmPh7@z/p7@ZY3A7l19zMA7pC@76/7pOtrVrSUHw).
Ungolfed:
```
t; // temporary varaiable fpr swapping characters
r(char *s) { // helper function to reverse a string: takes a string argument and modifies it
    char *e = s + strlen(s) - 1; // find the end of the string
    for(; e > s; // move the end pointer and the start pointer towards each other until they meet
        *e-- = *s, *s++ = t) // swap the characters under the start and end pointers ...
        t = *e; // ... using the temporary variable
}
g(o, // function for the 196 algorithm: takes an int argument and returns an int
  l, f) { // abusing the argument list to declare to extra variables: one is a string for reversing the number, the other is an int
    for(l = malloc(9); // allocate space for the string
        sprintf(l, "%d", o), // convert the number to a string
        r(l), // reverse that string
        f = atoi(l), // convert it back to an int
        f - o; ) // loop until the two numbers are equal
        o += f; // add the two numbers
}
```
[Answer]
# Powershell, ~~63~~ 62 bytes
*-1 byte thanks to @AdmBorkBork*
```
param($m)for(;$m-$s;$m=-join"$s"[-1..-"$s".Length]){$s+=$m};$s
```
Test script:
```
$f = {
param($m)for(;$m-$s;$m=-join"$s"[-1..-"$s".Length]){$s+=$m};$s
}
&$f 5280
```
]