# Print the Nth non-palindromic number

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.

## Rules

• 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

1
==> 10

-----

5
==> 15

-----

12
==> 23


## Scoring

This is , so least bytes wins.

## Submissions

# 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 COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

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

}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(a) {
});
comment_page = 1;
}
});
}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
});
else process();
}
});
}

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

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

function process() {
var valid = [];

var body = a.body;
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});

var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
});

});

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;
++place;

.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)

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.push(languages[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)
language = jQuery(language);
jQuery("#languages").append(language);
}

}
body { text-align: left !important}

width: 290px;
float: left;
}

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

font-weight: bold;
}

table td {
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>

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

</tbody>
</table>
</div>
<table style="display: none">
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
</tbody>
</table>

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

# Pyth, 7 bytes

e.f!_I


Test suite

Explanation:

e.f!_I
e.f!_IZQ    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.


([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 ;0{<≜.↔¬}ⁱ⁽  -3 bytes tanks to Fatalize ## Explanation ; { }ⁱ⁽ -- 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! • ;İ{ℕ≜.↔¬}ᶠ⁽t is 2 bytes shorter. – Fatalize Aug 22 '18 at 7:06 • Actually, using iterate is 1 byte shorter: ;0{<≜.↔¬}ⁱ⁽ – Fatalize Aug 22 '18 at 7:09 # Jelly, 9 bytes 1 bytes thanks to @Sp3000. ṚḌ_ 0Ç³#Ṫ  Try it online! Test suite. ## Explanation 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. 0Ç³#Ṫ 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.  • Fun fact: try 123Ṛ – Sp3000 May 3 '16 at 15:47 • @Sp3000 Very interesting indeed! – Leaky Nun May 3 '16 at 15:53 • 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.) – Dennis May 3 '16 at 18:26 • Doesn't work for me... – Leaky Nun May 3 '16 at 23:03 • 7 bytes but it may use newer features – caird coinheringaahing Nov 2 '17 at 22:24 # 05AB1E, 8 bytes Code: µNÂÂQ>i¼  Uses CP-1252 encoding. Try it online!. • 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ÂÊ½. – Kevin Cruijssen Aug 21 '18 at 14:31 • @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. – Emigna Aug 21 '18 at 16:02 • @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.. – 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 for(;$j-lt$args[0]){if(++$i-ne-join"$i"["$i".length..0]){$j++}}$i


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.

### Examples

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

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

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

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


# 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)
else:
return f(n,test+1,count)


which itself is essentially:

def f(n):
test=0
count=1
while count<=n:
if str(test)!=reversed(str(test)):
count+=1
test+=1
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, 13311793 76 bytes

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

x=scan();while({F=F+any((D=T%/%10^(1:nchar(T)-1)%%10)!=rev(D));F<=x})T=T+1;T


Try it online!

• You can some some bytes abusing F, etc.: TIO. Also, why are you restricting the loop to (0:97)+10 ? – JayCe Aug 21 '18 at 19:13
• 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? – Giuseppe Aug 21 '18 at 20:01
• @Giuseppe Updated with your recommendations. Still a little confused on how to implement a while loop while at the same time saving bytes. – Robert S. Aug 21 '18 at 22:09
• @RobertS. if you have any questions, feel free to ping me in the R chatroom! – 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!

### Explanation

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
begin
10 /mod
>r swap
10 * +
r> ?dup 0=
until
;

: f ( s -- s )
9 swap 0
0
do
begin
1+ dup dup
reverse =
0= until
loop
;


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


### Usage:

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

;τR9+;$;R=YM@░E  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. Explanation: ;τR9+;$;R=YM@░E
;τ9+R;             push n, range(1,(2*n)+10)
$;R=YM@░ 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. d=(i,a=0)=>i?d(i-=++a!=[...''+a].reverse().join,a):a  ### Usage d=(i,a=0)=>i?d(i-=++a!=[...''+a].reverse().join,a):a d(1) 10 d(123) 146 d(7624) 7800 d(7625) // Uncaught RangeError: Maximum call stack size exceeded  ## JavaScript (ES6), 59 bytes Doesn't use recursion and so can handle much larger inputs. i=>eval("for(a=9;i-=++a!=[...${a}].reverse().join;);a")


### Usage

(i=>eval("for(a=9;i-=++a!=[...${a}].reverse().join;);a"))(1) 10 (i=>eval("for(a=9;i-=++a!=[...${a}].reverse().join;);a"))(7625)
7801
(i=>eval("for(a=9;i-=++a!=[...${a}].reverse().join;);a"))(123456) 124579  ## 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 ## 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. • 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; – ceilingcat Jan 2 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. f=->x,y=?9{x<1?y:(y.next!.reverse!=y)?f[x-1,y]:f[x,y]}  Ungolfed: def f(x, y="9") if x<1 return y else y = y.next if y.reverse != y return f(x-1, y) else return f(x, y) end end end  ## 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;}  • @enedil regarding your edit: #import is an compiler extension of gcc. It is deprecated, but this doesn't really matter here – ovs Dec 8 '17 at 13:55 # APL NARS 35 chars r←v a;c r←c←0 A:r+←1⋄c+←r≠⍎⌽⍕r⋄→A×⍳c<a  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 10 h 1.32 ¯1 h 7878 8057 h¨3 5 12 13 15 23 h 6 7 8 ¯1 h '123' ¯1 h '1' ¯1 h 1.0 10 h 1.0003 ¯1 h ¯2 ¯1 h 0 ¯1 h 200000 201200 h 200001 ¯1  # Husk, 6 bytes Yay for ↔ :) !fS≠↔N  Try it online! ### Explanation  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 map{1until++$\!=reverse$\}1..$_}{


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

n=>
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

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

# Japt, 14121110 9 bytes

1-indexed

@UµX¦sw}f


Try it

# Java 8, 11795 94 bytes

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


0-indexed

Explanation:

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

• @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. – Kevin Cruijssen Jan 3 at 9:13

## TCC, 11 bytes

?>!~<>;i;'T


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"

• 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. – Dennis Jul 26 '16 at 17:07
• @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. – Jonathan Frech Aug 21 '18 at 14:38