A palindromic number (in case you don't know) is a number which reads the same backwards and forwards (example, 11). The first 15 non-palindromic numbers are: 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26. This is A029742. I constantly need these numbers, but my sticky note pad is very small, so your code must be as short as possible.


  • Each submission must be a full program or function (e.g. in C, you can't just define a function without headers, but you can define a function WITH necessary headers ).
  • If it is possible, provide a link to a site where your program can be tested.
  • Your program must not write anything to STDERR.
  • You can take input as an argument or from STDIN (or the closest alternative in your language).
  • Programs are scored according to bytes. The usual character set is UTF-8, if you are using another please specify.
  • Standard loopholes are forbidden.

Test Cases

==> 10


==> 15


==> 23


This is , so least bytes wins.


To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:

# [><>](http://esolangs.org/wiki/Fish), 121 bytes


Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 79251; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;

function getAnswers() {
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answers_hash[id] = a;
      if (!data.has_more) more_answers = false;
      comment_page = 1;

function getComments() {
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();


var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;

function process() {
  var valid = [];
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    var match = body.match(SCORE_REG);
    if (match)
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();
    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;

  for (var i = 0; i < langs.length; ++i)
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);

body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;

#language-list {
  padding: 10px;
  width: 290px;
  float: left;

table thead {
  font-weight: bold;

table td {
  padding: 5px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <table class="answer-list">
    <tbody id="answers">

<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <tbody id="languages">

<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>

  • 1
    \$\begingroup\$ Any testcases ? \$\endgroup\$ – Leaky Nun May 3 '16 at 15:17
  • \$\begingroup\$ @KennyLau I'll do some. \$\endgroup\$ – George Gibson May 3 '16 at 15:18
  • \$\begingroup\$ Can we use a 0-based index, so 15 would be the 4th number? \$\endgroup\$ – nimi May 3 '16 at 15:58
  • \$\begingroup\$ @nimi Either, but please specify if yours is 0-indexed. \$\endgroup\$ – George Gibson May 3 '16 at 16:29
  • \$\begingroup\$ @nimi Sorry, that's what I meant, have edited to clarify. \$\endgroup\$ – George Gibson May 3 '16 at 16:34

25 Answers 25


Pyth, 7 bytes


Test suite


e.f!_I`ZQ    Implicit variable introduction.
 .f     Q    Find the first Q numbers whether the following is truthy,
             starting at 1, where Q is the input.
      `Z     Convert the number to a string.
     _I      Check if it's the same when reversed.
    !        Logical not.
 e           Return the last element of the list.

Haskell, 38 bytes

([x|x<-[1..],(/=)<*>reverse$show x]!!)

Uses 0-based index. ([x|x<-[1..],(/=)<*>reverse$show x]!!) 11 -> 23.

The test whether to keep a number (/=)<*>reverse$show x translates to (show x) /= (reverse (show x)), i.e check if the string representation of the number does not equal the reverse of the string representation.


Brachylog, 14 11 bytes


-3 bytes tanks to Fatalize


; {      }ⁱ⁽        --  Find the nth number
 0                  --      (starting with 0)
   <                --      which is bigger then the previous one
    ≜               --      make explicit (otherwise it fucks up)
      .             --      which is the output
       ↔            --      and if reversed
        ¬           --      is not the output

Try it online!

  • \$\begingroup\$ ;İ{ℕ≜.↔¬}ᶠ⁽t is 2 bytes shorter. \$\endgroup\$ – Fatalize Aug 22 '18 at 7:06
  • \$\begingroup\$ Actually, using iterate is 1 byte shorter: ;0{<≜.↔¬}ⁱ⁽ \$\endgroup\$ – Fatalize Aug 22 '18 at 7:09

Jelly, 9 bytes

1 bytes thanks to @Sp3000.


Try it online!

Test suite.


DUḌ_   Helper link. Check if x is not palindrome.

D      Convert to decimal.
 U     Reverse.
  Ḍ    Convert back to integer.
   _   Subtract x from the result above.
       For 23, this will yield 32-23 = 9.
       Only yield 0 (falsy) if x is palindrome.
       If x is not a palindrome,
       it will return a truthy number.

0dz#Ṫ  Main link.

0      Start from 0.
   #   Find the first         numbers:
  ³                   <input>
 Ç         where the above link returns a truthy number.
    Ṫ  Yield the last of the matches.
  • 1
    \$\begingroup\$ Fun fact: try 123Ṛ \$\endgroup\$ – Sp3000 May 3 '16 at 15:47
  • \$\begingroup\$ @Sp3000 Very interesting indeed! \$\endgroup\$ – Leaky Nun May 3 '16 at 15:53
  • \$\begingroup\$ You can drop the ³. If you place the input on STDIN, you can drop the 0 as well. (In the latest version of Jelly, ṚḌ_ø#Ṫ works too, but it is newer than this challenge.) \$\endgroup\$ – Dennis May 3 '16 at 18:26
  • \$\begingroup\$ Doesn't work for me... \$\endgroup\$ – Leaky Nun May 3 '16 at 23:03
  • \$\begingroup\$ 7 bytes but it may use newer features \$\endgroup\$ – caird coinheringaahing Nov 2 '17 at 22:24

05AB1E, 8 bytes



Uses CP-1252 encoding. Try it online!.

  • \$\begingroup\$ This has most likely something to do with the old version of 05AB1E, but out of curiosity: why the double bifurcated Â? PS for anyone else reading this: Can now be 5 bytes µNÂʽ. \$\endgroup\$ – Kevin Cruijssen Aug 21 '18 at 14:31
  • \$\begingroup\$ @KevinCruijssen: Likely due to no implicit output of N (only top of stack). Also, it can be 4 bytes now as the ½ is also implicit. \$\endgroup\$ – Emigna Aug 21 '18 at 16:02
  • \$\begingroup\$ @Emigna Ah, completely forgot about ½ being implicit, even though I mentioned it in a tip I wrote myself.. >.< Thought the ¼ (increase counter_variable by 1) was implicit for the while-loop µ for a moment, but it's indeed the ½ (if top of the stack is 1: increase counter_variable by 1) instead.. \$\endgroup\$ – Kevin Cruijssen Aug 21 '18 at 17:54

Clojure, 62 bytes

#(nth(for[i(range):when(not=(seq(str i))(reverse(str i)))]i)%)

0-indexed. Generate lazily infinite range of non-palindromic numbers using list comprehension and take ith one. See it online: https://ideone.com/54wXI3


PowerShell v2+, 65 bytes


Loops through numbers from 0 (implicit value for uninitialized $i) until we find input $args[0] many matches, then outputs the last one. Note that we don't initialize the loop, so $j=0 is implicit.

Each iteration, we pre-increment $i, and check if it's not-equal to $i reversed. If so, that means we've found a non-palindrome, so increment $j. The loop then continues as many times as necessary.


PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 100

PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 5

PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 55

PS C:\Tools\Scripts\golfing> .\print-nth-palindromic-number.ps1 212

Python 2, 60 bytes

f=lambda n,i=0,j=1:j>n and i-1or f(n,i+1,j+(`i`!=`i`[::-1]))

A one-indexed function that takes input of n via argument and returns the nth non-palindromic number.

How it works

This is an exhaustive recursive search, which consecutively tests integers i in the range [1,∞) until n non-palindromic numbers have been found; since i is pre-incremented, i-1 is then returned. Testing whether a number is palindromic is performed by converting to a string, reversing, and then checking whether the original and reversed strings are equal.

The code is logically equivalent to:

def f(n,test=0,count=1):
    if count>n:
        return test
    elif str(test)!=reversed(str(test)):
        return f(n,test+1,count+1)
        return f(n,test+1,count)

which itself is essentially:

def f(n):
    while count<=n:
        if str(test)!=reversed(str(test)):
    return test-1

Try it on Ideone


Clojure, 62 bytes

#(nth(filter(fn[i](not=(seq i)(reverse i)))(map str(range)))%)

A quite different approach than the other answer, but equal length.


R, 133 117 93 76 bytes

-16 bytes thanks to JayCe. -41 bytes thanks to Giuseppe.


Try it online!

  • 1
    \$\begingroup\$ You can some some bytes abusing F, etc.: TIO. Also, why are you restricting the loop to (0:97)+10 ? \$\endgroup\$ – JayCe Aug 21 '18 at 19:13
  • 1
    \$\begingroup\$ use tip #3 from my answer Tips for Golfing in R to extract the digits; you can do all(D==rev(D)) where D is a vector of digits. I believe a while loop will be shorter, and as @JayCe asks, why are you only checking numbers between 10 and 107? \$\endgroup\$ – Giuseppe Aug 21 '18 at 20:01
  • \$\begingroup\$ @Giuseppe Updated with your recommendations. Still a little confused on how to implement a while loop while at the same time saving bytes. \$\endgroup\$ – Robert S. Aug 21 '18 at 22:09
  • 1
    \$\begingroup\$ @RobertS. if you have any questions, feel free to ping me in the R chatroom! \$\endgroup\$ – Giuseppe Aug 22 '18 at 14:38

Forth (gforth), 103 99 bytes

: f 9 swap 0 do begin 1+ dup 0 over begin 10 /mod >r swap 10 * + r> ?dup 0= until = 0= until loop ;

Try it online!


Loop n times, each iteration finds the next non-palindromic number by incrementing a counter by 1 until the number doesn't equal itself reversed

Ungolfed Code

Normally I wouldn't "ungolf" the code, but since this code is somewhat messy I figured it would help

: reverse ( s -- s )
    0 swap 
        10 /mod
        >r swap
        10 * +
        r> ?dup 0=

: f ( s -- s )
    9 swap 0
            1+ dup dup
            reverse =
        0= until

Code Explanation

: f                \ start a new word definition
  9                \ start at 9, since all positive ints < 10 are palindromic
  swap 0           \ set up loop parameters from 0 to n-1
  do               \ start a counted loop       
    begin          \ start an indefinite loop
      1+ dup       \ increment counter and place a copy on the stack
      ( Reverse )
      0 over       \ add 0 to the stack (as a buffer) and copy the top counter above it
      begin        \ start another indefinite loop
        10 /mod    \ get the quotient and remainder of dividing the number by 10
        >r         \ store the quotient on the return stack
        swap 10 *  \ multiply the current buffer by 10
        +          \ add the remainder to the buffer
        r>         \ grab the quotient from the return stack
        ?dup       \ duplicate if not equal to 0
        0=         \ check if equal to 0
      until        \ end inner indefinite loop if quotient is 0
      ( End Reverse )
      = 0=         \ check if counter =/= reverse-counter            
    until          \ end the outer indefinite loop if counter =/= reverse-counter
  loop             \ end the counted loop
;                  \ end the word definition 

Perl 6, 29 bytes

{grep({$_!= .flip},^Inf)[$_]}

( uses 0 based index )

{         # The $_ is implied above
  grep(   # V
    { $_ != $_.flip }, # only the non-palindromic elements of
    ^Inf               # an Infinite list ( 0,1,2,3 ...^ Inf )
  )[ $_ ]              # grab the value at the given index


my &non-palindrome = {grep({$_!= .flip},^Inf)[$_]}

say non-palindrome 1  - 1; # 10
say non-palindrome 5  - 1; # 15
say non-palindrome 12 - 1; # 23

# this also works:
say non-palindrome 0..20;
# (10 12 13 14 15 16 17 18 19 20 21 23 24 25 26 27 28 29 30 31 32)

Actually, 17 bytes


Try it online!

Values are 1-indexed. This could be easily changed to 0-indexed by replacing the first R with r. But, R is what I initially typed, so that's what I'm going with.

The nonpalindromic numbers satisfy a(n) ≈ n + 10, so 2n+9 is a sufficient upper bound.


;τ9+R;             push n, range(1,(2*n)+10)
      `$;R=Y`M@░   take values that are not palindromic
                E  take nth element

JavaScript (ES6), 54 bytes

Uses 1-based indexing. Only works up until the 7624th number.



// Uncaught RangeError: Maximum call stack size exceeded

JavaScript (ES6), 59 bytes

Doesn't use recursion and so can handle much larger inputs.




Javascript (using external library) (97 bytes)

n=>_.Sequence(n,i=>{i=_.From(i+"");if(!i.Reverse().SequenceEqual(i)){return i.Write("")}}).Last()

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: Library has static method called Sequence, where first param defines how many elements the sequence will guarantee to create, and the 2nd parameter is a predicate accepting the current iteration value, "i". The predicate converts the integer to a string, which gets converted to a char array by calling _.From. The char array is compared against the reversal of the char array, and if they are not equal the char array is joined back into a string and returned. Otherwise, nothing is returned (i.e the result is undefined, which the library will always ignore). Finally, the last element of the sequence, i.e the Nth element is returned

enter image description here


C, 84 bytes

Function f(n) takes integer n and returns n-th non-palindromic number (1 based).

g(n,r){return n?g(n/10,r*10+n%10):r;}s;f(n){for(s=9;n--;g(++s,0)==s&&s++);return s;}

Test it on Ideone!

It's fairly trivial code, thus there is probably space for improvement.

  • \$\begingroup\$ Suggest n=n?g(n/10,r*10+n%10):r;}s;f(n){for(s=9;n--;g(++s,0)-s||s++);n=s; instead of return n?g(n/10,r*10+n%10):r;}s;f(n){for(s=9;n--;g(++s,0)==s&&s++);return s; \$\endgroup\$ – ceilingcat Jan 2 '19 at 22:36

Ruby, 54 bytes

This function is 1-indexed and is partially based on Dom Hastings's Javascript answer. I think there's a way to golf this better, especially with that last ternary condition. Also, this function currently returns a string, which may need to be edited later. Any golfing suggestions are welcome.



def f(x, y="9")
 if x<1
  return y
  y = y.next
  if y.reverse != y
   return f(x-1, y)
   return f(x, y)

C++ (GCC), 148 bytes

It's 1-based and the algorithm is really naive

#import <iostream>
using namespace std;int n,i=1;string s;main(){cin>>n;while(s=to_string(i+1),(n+=equal(begin(s),end(s),s.rbegin()))-i++);cout<<i;}
  • \$\begingroup\$ @enedil regarding your edit: #import is an compiler extension of gcc. It is deprecated, but this doesn't really matter here \$\endgroup\$ – ovs Dec 8 '17 at 13:55

APL NARS 35 chars

r←v a;c

it is the function v; "⍎⌽⍕"r traslate number r in string, reverse that string, traslate from string to number. Test and help functions:

  ⍝ return the one string for the basic types ('Char', 'Int', 'Float', 'Complex or Quaternion or Oction')
  ⍝ or one string for composite types ('Tensor 3' 'Tensor 4' etc 'Matrix', 'List', 'String')
  ⍝ follow the example in: https://codegolf.stackexchange.com/a/39745
  type←{v←⍴⍴⍵⋄v>2:'Tensor ',⍕v⋄v=2:'Matrix'⋄(v=1)∧''≡0↑⍵:'String'⋄''≡0↑⍵:'Char'⋄v=1:'List'⋄⍵≢+⍵:'Complex or Quaternion or Oction'⋄⍵=⌈⍵:'Int'⋄'Float'}
  h←{'Int'≢type ⍵:¯1⋄(⍵<1)∨⍵>2e5:¯1⋄v ⍵} 
  h 1
  h 1.32
  h 7878
  h¨3 5 12
13 15 23 
  h 6 7 8
  h '123'
  h '1'
  h 1.0
  h 1.0003
  h ¯2
  h 0
  h 200000
  h 200001

Husk, 6 bytes

Yay for :)


Try it online!


 f   N  -- filter the naturals by:
  S≠    --   is it not equal to..
    ↔   --   ..itself reversed
!       -- index into that list

Perl 5, 33 + 1 (-p) = 34 bytes


Try it online!


C# 7, 89 bytes

n=>{int i=9;for(;n-->0;)if(Enumerable.SequenceEqual(++i+"",(""+i).Reverse()))i++;return i;}

1 indexed Try on Repl.It

  int i = 9;                                  | Start at 9. Iterate exactly n times. Assume n >= 1      
  for(;n-->0;)                                | Iterate n times
  if(EnumerableSequenceEqual(                 | Compare two sequences
  ++i+"",(""+i).Reverse())                    | Generate the forward and backward strings, which behave like char sequences for Linq
  i++                                         | If the sequences are equal, the number is a palindrome. Increment i to skip
  return i;                                   | Return the number after the for loop exits

I don't think this uses any language features from c# 7, but I put there since that's what I tested against

  • \$\begingroup\$ Welcome to PPCG. \$\endgroup\$ – Jonathan Frech Aug 22 '18 at 0:34

Japt, 14 12 11 10 9 bytes



Try it


Java 8, 117 95 94 bytes

n->{int r=10;for(;n-->0;)if((++r+"").contains(new StringBuffer(r+"").reverse()))r++;return r;}



Try it here.

n->{             // Method with integer as both parameter and return-type
  int r=10;      //  Result-integer, starting at 10
  for(;n-->0;)   //  Loop an amount of times equal to the input
    if((++r+"")  //   First raise `r` by 1, and then check if `r`
               .contains(new StringBuffer(r+"").reverse()))
                 //   is the same as `r` reversed (and thus a palindrome)
      r++;       //    And if it is: raise `r` by 1 again
  return r;}     //  Return result-integer
  • \$\begingroup\$ @ceilingcat That gives incorrect results.. new StringBuffer(int) is not equal to new StringBuffer(String), nor is String.equals(StringBuffer) instead of String.equals(String).. This is an old answer however, so I can use (++r+"").contains(new StringBuffer(r+"").reverse()) to save 1 byte. \$\endgroup\$ – Kevin Cruijssen Jan 3 '19 at 9:13

TCC, 11 bytes


Try it online!

            | Printing is implicit
?>          | Find n-th number for which the following is "T":
  !~        | If not equal...
    <>;     | reverse. No value specified, so input is assumed.
       i;   | Input, since double semicolons are ignored
         'T | ... print string "T"
  • 1
    \$\begingroup\$ This does not work with the tcc.lua file with timestamp 16-07-26 12:46 UTC, which didn't have the ?> command. If your answer requires a version of the language that postdates the challenge, you must label it as non-competing in the header. I'll remove my downvote when you do. \$\endgroup\$ – Dennis Jul 26 '16 at 17:07
  • \$\begingroup\$ @Dennis I stumbled over this two year old post and wanted to mention that answers are now no longer to be marked non-competing when their language post-dates the challenge. \$\endgroup\$ – Jonathan Frech Aug 21 '18 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.