196 algorithm code golf

35

5

Write a short program for 196-algorithm. 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 (that is, it does eventually yield a palindrome under this algorithm, rather than continuing infinitely)

Output

the palindrome reached.

Eelvex

Posted 2011-01-28T20:56:27.570

Reputation: 5 204

I'm assuming you expect it to work for all positive integers not in A023108?

– Mr. Llama – 2012-03-08T22:58:48.537

@GigaWatt It should at least work for all positive integers that fit in the <integer> type of the language that you use. – Eelvex – 2012-03-09T05:50:21.200

@Eelvex - So... when the input is 196, what's the expected output? It fits in the integer data type quite comfortably. – Mr. Llama – 2012-03-09T15:39:38.947

@GigaWatt the expected output in this case is the palindrome reached with input 196, but since we wouldn't want to wait forever, I won't ask you to try it. – Eelvex – 2012-03-09T16:02:14.307

1@GigaWatt also, I had missread your fist question :) Just don't bother with A023108s' case. – Eelvex – 2012-03-09T16:03:44.943

@Eelvex: How will Lychrel numbers be handled? – Joel Cornett – 2012-05-27T12:36:42.390

1@Joel, as with A023108, just ignore them (act like you don't know about them); we don't know if any exists anyway. – Eelvex – 2012-05-27T15:02:16.663

@Nakilon please give a reason for your edit. – Eelvex – 2011-01-29T08:31:09.733

6Because your question is probably the only one involving the 196 algorithm. Making single-use tags is not useful. – Chris Jester-Young – 2011-01-29T08:48:48.703

@Chris: It's a private beta with 34 questions so far; single-use tags is a normal thing at this point. Anyway, let's leave it as it is for now, retagging later is always an option :) – Eelvex – 2011-01-29T09:07:29.640

2What I meant was, your question is likely to be the only one ever to involve this topic, even in 2 years' time. :-) – Chris Jester-Young – 2011-01-29T09:12:34.267

1@Chris: Well, 196-algorithm is a pretty popular one, going by many different names. Just to be sure, though, I'll post another question about it before the 2-year-time lapses ;) – Eelvex – 2011-01-29T09:49:42.537

Answers

10

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

Dillon Cower

Posted 2011-01-28T20:56:27.570

Reputation: 2 192

2It saves a few characters to use numeric input. {⍵=A←⍎⌽⍕⍵:⍵⋄∇A+⍵}⎕. You save the braces, a reverse and an eval. – marinus – 2012-05-27T07:38:04.160

10

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

Alexandru

Posted 2011-01-28T20:56:27.570

Reputation: 5 485

Hehe ..)))))))) – Nakilon – 2011-01-28T21:53:04.467

2

By looking at n as an int you can shorten by 6 characters, check for the code: http://meta.codegolf.stackexchange.com/q/75/62

– JPvdMerwe – 2011-01-28T22:39:17.917

Seems I accidentally included the new line vim sneakily added to the end of my file to my count. The real count is 55. – JPvdMerwe – 2011-01-29T18:56:33.153

10

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).

Chris Jester-Young

Posted 2011-01-28T20:56:27.570

Reputation: 4 464

@M28 look at my answer, that's what I call random keys on keyboard! – Ali1S232 – 2012-03-23T14:32:12.010

4Are you sure you didn't press random keys on your keyboard? It looks like that... – None – 2011-01-29T03:03:23.807

1@M28: GolfScript looks even more like line noise than Perl, doesn't it? ;-) – Chris Jester-Young – 2011-01-29T03:10:41.133

I feel sorry for you, it must be painful to code that – None – 2011-01-29T03:51:41.283

@M28: That wasn't nearly as painful as the solution I wrote for Luhn algorithm. Just think about that. :-P

– Chris Jester-Young – 2011-01-29T04:33:24.213

Your family is worried about you – None – 2011-01-29T04:36:30.840

7

Ruby — 56 chars

x,r=gets
x="#{x.to_i+r.to_i}"until x==r=x.reverse
puts x

Nakilon

Posted 2011-01-28T20:56:27.570

Reputation: 605

7

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())

swstephe

Posted 2011-01-28T20:56:27.570

Reputation: 649

Just trying some old challenges, already answered, so not serious contender. – swstephe – 2014-12-23T19:28:56.823

1Some challenge authors will update the accepted answer if a shorter solutions comes in, so I think it's fair to inform the OP, that this is not technically a valid submission. (Don't get me wrong, I like to answer old challenges with CJam for fun, too - and I just did a few minutes ago. I'm just saying, if you do, leave a note, that the language is newer than the challenge.) – Martin Ender – 2014-12-23T19:30:20.973

Actually being "not a serious contender" makes an answer subject to deletion -- but I don't see any reason this shouldn't be considered a serious contender. – pppery – 2019-08-29T04:02:32.477

6

J 25 27 31

f=:(+g)^:(~:g=.|.&.":)^:_
e.g.
f 5280
23232

Eelvex

Posted 2011-01-28T20:56:27.570

Reputation: 5 204

6

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

Optimizer

Posted 2011-01-28T20:56:27.570

Reputation: 25 836

5

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

Tom

Posted 2011-01-28T20:56:27.570

Reputation: 191

4

Python: 66

n=input()
while 1:
 r=int(`n`[::-1])
 if n==r:break
 n+=r
print n

marcog

Posted 2011-01-28T20:56:27.570

Reputation: 10 244

4

Brachylog, 8 bytes

↔?|↔;?+↰

Try it online!

Somewhat similar to one of the first Brachylog programs I saw and was intrigued by, from the Brachylog introduction video.

?↔?.|↔;?+↰.  (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

sundar - Reinstate Monica

Posted 2011-01-28T20:56:27.570

Reputation: 5 296

4

Scala 82

def p(n:Int):Int={val s=n.toString.reverse.toInt
if(n==s)n else p(n+s)}
p(readInt)

user unknown

Posted 2011-01-28T20:56:27.570

Reputation: 4 210

4

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

globby

Posted 2011-01-28T20:56:27.570

Reputation: 1 132

Edited. @Optimizer – globby – 2014-12-24T06:47:40.217

Please don't edit all your submissions at once for minor edits (like a version number), as this unnecessarily clutters the front page. It's fine if you do 2 or maybe 3 at a time, but please wait a few hours before doing more systematic edits. – Martin Ender – 2014-12-30T00:51:57.557

Forgot that it would push to front page, my bad. @MartinBüttner – globby – 2014-12-30T00:52:24.973

4

Perl, 40 chars

$_=<>;$_+=$r while$_!=($r=reverse);print

ninjalj

Posted 2011-01-28T20:56:27.570

Reputation: 3 018

I know this is a really old post but a few changes can reduce this to 26 bytes: Try it online!

– Dom Hastings – 2018-08-01T09:34:58.510

4

05AB1E, 7 bytes (non-competing)

Non-competing, since the language postdates the challenge.

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!.

Adnan

Posted 2011-01-28T20:56:27.570

Reputation: 41 965

Could you explain a little more on the process of bifurcation? – Conor O'Brien – 2016-07-28T18:41:51.050

1@CᴏɴᴏʀO'Bʀɪᴇɴ For example, on the stack is the string hello. The bifurcation will keep the original string, and pushes the string reversed. It's short for duplicate and reverse. – Adnan – 2016-07-28T18:43:42.273

Oh, I see. Cool! Thanks – Conor O'Brien – 2016-07-28T18:51:29.753

3

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!

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.

z3r0

Posted 2011-01-28T20:56:27.570

Reputation: 31

Wow, not everyone uses Jelly in their first post. – Nissa – 2018-04-25T14:36:36.007

It was on my to-do list to post an answer on PPCG using an esoteric language. Jelly happened to be the first one I thought of :) – z3r0 – 2018-04-25T14:40:12.473

3

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

sinedcm

Posted 2011-01-28T20:56:27.570

Reputation: 410

3

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.

KeithS

Posted 2011-01-28T20:56:27.570

Reputation: 211

1You can easily golf it more. Use ""+ rather than .ToString and get rid of some spaces. – Jacob – 2014-12-30T04:46:37.163

3

Bash (64)

X=`rev<<<$1|sed s/^0*//`;[ $1 = $X ]&&echo $1||. $0 $(($1+$X))

Call with: bash <filename> <number>

marinus

Posted 2011-01-28T20:56:27.570

Reputation: 30 224

What is the <filename> for? – Eelvex – 2012-03-09T05:50:41.603

2@Eelvex the script needs to call itself so you need to store it in a file. – marinus – 2012-03-12T14:52:44.173

3

r=input()
while 1:
    r=`r`
    if r==r[::-1]:
      break
    else:
      r=int(r)+int(r[::-1])

print r

Ashwini Chaudhary

Posted 2011-01-28T20:56:27.570

Reputation: 169

3

PHP - 54 48 characters

<?for($s=`cat`;$s!=$r=strrev($s);$s+=$r);echo$s;

Test:

$ php 196.php <<< 5280
23232

Arnaud Le Blanc

Posted 2011-01-28T20:56:27.570

Reputation: 2 286

I'm going to have to remember the $str =cat`` thing for future golfing. Heck of a lot better than using STDIN and still better than $argv[0]. – Mr. Llama – 2012-03-08T23:01:45.363

@GigaWatt: $s='m4' should also work. – ninjalj – 2012-11-23T20:49:16.897

2

Add++, 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!

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]

caird coinheringaahing

Posted 2011-01-28T20:56:27.570

Reputation: 13 702

2

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)

Thomas O

Posted 2011-01-28T20:56:27.570

Reputation: 3 044

The task description states that only the final palindrome should be printed. – Joey – 2011-01-29T12:00:59.460

2

GNU dc, 46 bytes

Requires GNU dc, min version 1.4 (for R command).

[O~3RO*+rd0<R]sR[+lfx]sg[ddO~rd0<R+d3R!=g]dsfx

Input and output are top-of-stack, as usual. It takes a surprising amount of code to reverse digits in dc (unless I'm missing something, which is far from impossible). It does have the numeric range to behave nicely with inputs such as these (which will overflow 32-bit unsigned arithmetic, for example):

  • 89 ⇒ 8,813,200,023,188
  • 8997 ⇒ 16,668,488,486,661
  • 10677 ⇒ 4,668,731,596,684,224,866,951,378,664

Explanation

# Reverse digits, starting after first digit extracted
[O~3RO*+r d0<R]sR

# Recursion helper - add and recurse
[+ lfx]sg

# Main recursive function
[dd O~r d0<R+ d3R !=g]dsfx

Toby Speight

Posted 2011-01-28T20:56:27.570

Reputation: 5 058

Try it online! (Javascript) – Toby Speight – 2018-08-02T14:11:23.827

Might want to specify that this works only on GNU dc 1.4 and later, since it uses the new R command. Good solution, though! – Sophia Lechner – 2018-08-03T18:29:46.040

I'm working on a totally different approach but not sure it will wind up smaller. – Sophia Lechner – 2018-08-03T18:31:38.020

Thanks Sophia - I hadn't realised that R was new. Looking forward to seeing your method! – Toby Speight – 2018-08-06T07:15:04.680

Ah, nope...I tried a different approach to arranging the outside loop but it ended up about five bytes larger and no prettier. You win. =) – Sophia Lechner – 2018-08-06T16:27:01.570

2

R, 193 109 105 bytes

-84 bytes thanks to Giuseppe! -4 byes thanks to JayCe!

function(x){"-"=utf8ToInt
S=strtoi
"!"=rev
while({z=paste(S(x)+S(intToUtf8(!-x),10));any(-z!=!-z)})x=z
z}

Try it online!

Robert S.

Posted 2011-01-28T20:56:27.570

Reputation: 1 253

1You can (and should) choose a different way of doing this than string manipulation, but here are some golfing tips for the method you've chosen: strsplit(x,"") is shorter than strsplit(x,NULL), and el(L) is shorter than L[[1]]. as.double is shorter than as.numeric and strtoi is shorter than both; instead of setting t just use it directly in your if statement. also this is a recursive function if I'm not mistaken, so you need to put f= as part of your submission. – Giuseppe – 2018-08-02T15:51:32.110

@Giuseppe Got it. Thanks for the tips. I'll keep working on this. It's easier for me to just get something that works then go back and optimize. – Robert S. – 2018-08-02T16:01:05.813

1Hehehe, no worries. If you're hell-bent on using strings (or forced to by the problem), consider utf8ToInt to convert to digits and intToUtf8 to convert back. That'll be a big byte saving! – Giuseppe – 2018-08-02T16:07:21.420

1Here is a 109 bytes golf using utf8ToInt and a while loop – Giuseppe – 2018-08-02T17:58:37.170

@Giuseppe That is very helpful. I was running into issues with trying to add the two utf8ToInt converted numbers. Funny enough, using a recursive function instead of a while loop results in 108 byes assuming I don't have to put f=. Were you able to figure out if that was allowed?

– Robert S. – 2018-08-02T18:52:32.083

You must use f= if it is recursive, unfortunately. – Giuseppe – 2018-08-02T19:04:58.837

1Save 4 more bytes by using - in place of U. I also replaced rev with ! but it does not save any byte... – JayCe – 2018-08-06T17:02:44.287

@JayCe Interesting way to save bytes. Thanks! – Robert S. – 2018-08-06T17:05:40.197

2

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

mazzy

Posted 2011-01-28T20:56:27.570

Reputation: 4 832

1You don't need the ; between param($m) and for. – AdmBorkBork – 2018-08-03T14:01:57.930

2

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.

Joey

Posted 2011-01-28T20:56:27.570

Reputation: 12 260

Can be shortened by two characters if there only ever are ten digits of input. This way it's safe for long as well which is the largest integral type PowerShell supports anyway but still, I waste two chars. – Joey – 2011-01-29T11:56:41.293

2

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.

sepp2k

Posted 2011-01-28T20:56:27.570

Reputation: 1 679

@hammar: You could use the function monad and save even more: Define r=(=<<read.reverse.show) and just use r(==)`until`r(+). Apart from that saving, it doesn't need to be a full program, a valid submission could just be the unnamed function from before. This brings you down to 41 bytes: Try it online!

– ბიმო – 2018-08-02T18:31:36.540

1You can shorten this quite a bit by taking advantage of the underused function until from the Prelude, as well as extracting the pattern of applying a binary operator to x and r x. Also, use readLn instead of getLine and read. The result saves 20 characters: f%x=f x$read.reverse.show$x;main=readLn>>=print.until((==)%)((+)%) – hammar – 2011-11-08T21:47:14.980

2

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.

Ali1S232

Posted 2011-01-28T20:56:27.570

Reputation: 417

2

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;
}

Dillon Cower

Posted 2011-01-28T20:56:27.570

Reputation: 2 192

2

Pyke, 13 bytes (noncompeting)

D`_b]D$XIsr)h

Try it here!

 `_b          -     int(reversed(str(num))
D   ]         -    [num, ^]
     D        -   _ = ^
      $       -  delta(^)
       XI     - if ^:
         s    -  num = sum(_)
          r   -  goto_start()
            h - _[0]

Blue

Posted 2011-01-28T20:56:27.570

Reputation: 26 661

1

Java, 90 84 bytes

n->{for(long t;(t=new Long(new StringBuffer(n+"").reverse()+""))!=n;)n+=t;return n;}

-6 bytes thanks to @O.O.Balance.

Try it online.

Explanation:

n->{           // Method with long as both parameter and return-type
  for(long t;  //  Temp-long, starting uninitialized
      (t=new Long(new StringBuffer(n+"").reverse()+""))
               //  Before every iteration, reverse the temp-long
      !=n;)    //  And loop as long as it's not equal to `n` yet
    n+=t;      //   Add this temp-long to the input
  return n;}   //  Return the modified input as result

Kevin Cruijssen

Posted 2011-01-28T20:56:27.570

Reputation: 67 575

1

Japt, 11 10 bytes

@¶ìw}a@±ìw

Try it

Shaggy

Posted 2011-01-28T20:56:27.570

Reputation: 24 623

1

PHP, 57 Bytes

Try it online!

Code, recursive function

function f($n){echo(strrev($n)!=$n)?f(strrev($n)+$n):$n;}

Explanation

function f($n){
    echo(strrev($n)!=$n)? #check if non-palindrome
        f(strrev($n)+$n): #true, call again with $n + reverse $n
        $n;               #false (is a palindrome) echo $n

}

Francisco Hahn

Posted 2011-01-28T20:56:27.570

Reputation: 591

1

Perl 6, 36 bytes

{($_,{$_+.flip}...{$_==.flip})[*-1]}

Try it online!

An anonymous code block that returns the last element of a sequence defined by:

  • The first element is the first parameter
  • The i+1th element is the ith element plus the reverse of itself
  • And ends when the element is equal to its reverse

Jo King

Posted 2011-01-28T20:56:27.570

Reputation: 38 234

1

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.

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
}

O.O.Balance

Posted 2011-01-28T20:56:27.570

Reputation: 1 499

119 bytes – ceilingcat – 2018-10-02T03:48:58.410

1

MATL, 18 bytes

`Vt2&P=?5M.}1MvUsT

Try it on MATL Online

         % (implicit input)
`        % do-while loop
  Vt     % convert the number into a string, duplicate it
  2&P    % flip the copy left-to-right
  =      % are they equal? 
    ?5M. % if yes, push the number back on the stack and exit
         % (implicit output display)
    }1M  % else, push the number and its reverse (as strings) again on to the stack
    vUs  % convert them to numbers and add them
    T    % "True" value to continue loop, this time with the sum as the input number
         % (implicit loop end)

sundar - Reinstate Monica

Posted 2011-01-28T20:56:27.570

Reputation: 5 296

1

Husk, 7 bytes

¤Ω`S↔=+

Try it online!

Alternatively we could use ΩS=↔S+↔ for the same amount of bytes, but I like the one above more.

Explanation

¤Ω`S↔=+
¤        -- compose the arguments of
 Ω       -- | iterate second function until first is truthy
         -- with
  `S     -- | flipped S: applying binary function to itself and
    ↔    -- | | itself reversed
         -- first function: check if palindrome (\x-> x == reverse x)
         -- second function: "196ify" (\x-> x + reverse x)

ბიმო

Posted 2011-01-28T20:56:27.570

Reputation: 15 345

1

Ruby, 55 bytes

l=->x{x.reverse==x ? x:l[(x.to_i+x.reverse.to_i).to_s]}

Different approach than the other Ruby one, ended up golfing it down to one byte fewer

Explanation: makes a lambda l that recursively calls itself, each time adding the number's reverse, until the string is a palindrome

Slightly less golfed version:

func = ->x do
  (x.reverse == x) ? x : func[(x.to_i + x.reverse.to_i).to_s]
end

Piccolo

Posted 2011-01-28T20:56:27.570

Reputation: 261

1

Excel VBA, 49 bytes

An immediate window function which takes input from range [A1] and outputs to the VBE immediate window.

n=[A1]:Do:n=n+r:r=StrReverse(n):Loop While n-r:?n

Taylor Scott

Posted 2011-01-28T20:56:27.570

Reputation: 6 709

1

Lua 5.3.3, 57 bytes

Takes i as input, prints output:

r=0while i~=r do i=i+r|0r=0+(i..""):reverse()end print(i)

More readable version:

r=0
while i~=r do
  i=i+r|0
  r=0+(i..""):reverse()
end
print(i)

Super simple. Just repeatedly adds i to its reverse until i is equal to its reverse. Then it just prints the new value of i.

GalladeGuy

Posted 2011-01-28T20:56:27.570

Reputation: 101

1

Actually, 16 bytes

;WX;$R≈+;$;R=YWX

Try it online!

Explanation:

;WX;$R≈+;$;R=YWX
;                 push a copy of n
 W            W   while top of stack is truthy:
  X                 pop and discard
   ;$R≈+            copy n, cast to string, reverse, cast to int, add
        ;$;R=Y      not palindrome (cast to string, copy, reverse, check inequality)
               X  pop and discard

Mego

Posted 2011-01-28T20:56:27.570

Reputation: 32 998

1

J, 27 bytes

(+&.".|.)^:(-.@-:|.)^:_&.":

Try it online!

Jonah

Posted 2011-01-28T20:56:27.570

Reputation: 8 729

1

Python 2, 53 bytes

f=lambda x,y=0:x if x==y else f(x+y,int(`x+y`[::-1]))

Try it online!

Matthew Jensen

Posted 2011-01-28T20:56:27.570

Reputation: 713

1

Dyalog APL, 17 bytes

{⍵+⍎⌽⍕⍵}⍣{⍺≡⍎⌽⍕⍺}

{⍵+⍎⌽⍕⍵} add argument and its reverse...
... until...
{⍺≡⍎⌽⍕⍺} ... the result is a palindrome.

Adám

Posted 2011-01-28T20:56:27.570

Reputation: 37 779

1

Javascript ES6, 56 bytes

f=a=>(g=_=>[...""+a].reverse().join``)()==a?a:f(a+ +g())

SuperJedi224

Posted 2011-01-28T20:56:27.570

Reputation: 11 342

0

Wren, 102 bytes

A super long program.

Fn.new{|x|
while(x!=x[-1..0])x=(Num.fromString(x)+Num.fromString(x[-1..0])).toString
System.write(x)
}

Try it online!

user85052

Posted 2011-01-28T20:56:27.570

Reputation: