# Shortest way to reverse a number

Write a function (or equivalent subprogram) to accept a single integer valued argument and return a (similarly typed) value found by reversing the order of the base-10 digits of the argument.

For example given 76543 return 34567

## locked by Dennis♦Jun 4 '16 at 18:34

This post has been locked while disputes about its content are being resolved. You may discuss this on meta if you have concerns.

Read more about locked posts here.

## migrated from stackoverflow.comJun 11 '11 at 11:29

This question came from our site for professional and enthusiast programmers.

• Go back to the time the number was a string, then reverse the string – pmg Jun 11 '11 at 10:54
• The idea of a "shortest algorithm" is somewhat specious, especially if you'll allow "any language." Think up an algorithm, and I'll give you a DSL with an appropriate "~" operator ... – Pointy Jun 11 '11 at 10:56
• Just a notice: any number ending with 0 becomes a shorter number of digits when reversed... – powtac Jun 11 '11 at 12:44
• I know an algorithm that takes no time at all, but only works on palindromic numbers ;) – schnaader Jun 11 '11 at 14:47
• Found time to do the re-write myself. I hope this remain the puzzle that eltond meant to pose. – dmckee Jun 12 '11 at 0:37

## 64 Answers

this is AS3 code, so you may need to make slight changes

function reverseData ( inData:String ):* {
var ar1 = inData.split(''); //Takes string value, split each digit into an array

var ar2 = ar1.reverse(); //Inverses the array direction
/* //OR (if not supported) [not AS3]
var ar2 = new Array();
for( var i:int = (ar1.length - 1); i > 0; i++ ) {
ar2.push( ar1[i] );
}
*/

var result = ar2.join();
return result;
}


It should work for a string equavalent (that should be easy to typecast)

For a javascript example...

function flip( inData ) {
return ( parseInt( (inData + '').split('').reverse().join('') ) );
}

alert( flip(123) );


Depends on what you mean by short (javascript):

alert(String(123).split('').reverse().join('')),

• this is short for sure :) – eltond Jun 11 '11 at 10:56
• alert((''+123).split('').reverse().join('')); – st0le Jun 12 '11 at 2:21
• Why not alert(prompt().split('').reverse().join('')); ? – Wolle Vanillebär Lutz Jul 2 '14 at 10:07

## C#

int reversed = Convert.ToInt32(String.Join<char>(null, 76543.ToString().Reverse()));

• int.Parse should be shorter. – Joey Jun 12 '11 at 10:24
• An anonymous user proposed editing this to int reversed = int.Parse(string.Join("", ("" + 76543).Reverse())); – Peter Taylor Sep 28 '11 at 8:03

k4 - 6 characters

"I"$|$


Examples:

  "I"$|$76543
34567
"I"$|$98765
56789


Explanation from right to left: ("I"$= cast to integer)(| = reverse)($ = convert to string)

# Perl (19 chars)

Simple:

$x=reverse (98765); ## Bash (15) read a;rev<<<$a


As a number of other entries do, '01234' becomes '43210' and '2340' becomes '0432'; i.e. in Python terms it does print reverse(raw_input()). If behaviour like print int(reverse(str(int(raw_input())))) is expected, it is a bit longer:

### Takes care of trailing zeroes (36)

read a;sed s.^0*..\;s.0*$..<<<$a|rev

• I think right count is 3: rev alone will suffice – F. Hauri Dec 1 '13 at 13:24
• “Write a function” – So I think the shortest solution is still 15 characters, but this way: r(){ rev<<<$1;}. (And even that is kind of cheating as the complete solutions is r(){ return rev<<<$1;}.) – manatwork Dec 2 '13 at 9:40
• @manatwork Shorter versions: r()(rev<<<$1) or r()(exit rev<<<$1). – jimmy23013 Jul 1 '14 at 21:20
• Cool trick, @user23013. – manatwork Jul 2 '14 at 10:57
• str(int(raw_input())) really? [Python 2] [str(int(input()))] [from your example print int(reverse(str(int(raw_input()))))] – Erik the Outgolfer Apr 16 '16 at 7:58

## in Q (20 characters)

f:{"I"$reverse -3!x}  Sample Usage: q)f 89478237 73287498  Use the k version of reverse (wrapped in parentheses) to make it shorter {"I"$(|:) -3!x}


also just define it as a lambda to take 2 chars off for a total of 15

# ruby (26)

The existing ruby answer wasn't a function/lambda, so here goes:

f=->i{i.to_s.reverse.to_i}


BaCon

PRINT REVERSE$(STR$(76543))


Replace 76543 with any number.

# Java

""+new StringBuilder(""+i).reverse();


## Brainfuck, 11

>,[>,]<[.<]

• This accepts any string, not just numbers (ASCII 48-57). – Erik the Outgolfer Apr 16 '16 at 8:00

# Pyth (3 chars)

Disclaimer: This answer is not participating, just for fun/reference.

Try it here

v_z


# TI-BASIC, 3532 31 (or 28) bytes

Takes input from the calculator's answer variable, which is whatever was last evaluated (like _ in the interactive python shell).

fPart(.1int(Ans10^(seq(A,A,~int(log(Ans+.5)),not(Ans
sum(Ans10^(cumSum(1 or Ans


10^( is 2NDLOG and ~ is ( - ), next to ENTER. Everything else can be found in the 2ND0 catalog.

If the program doesn't have to handle the possibility of 0 as input, it can be reduced to 28 bytes by changing ~int(log(Ans+.5)),not(Ans to ~int(log(Ans)),0.
Credit goes partially to Thomas Kwa for helping to golf this.

• Doesn't work with 0; you could easily fix this by replacing log(Ans) with log(Ans+.5) and int( with iPart(. The shortest I found in a few minutes with a forwards list of digits was fPart(.1int(Ans10^(seq(A,A,~int(log(Ans)),0:sum(Ans10^(cumSum(1 or Ans; this can probably be improved. Overall, good work! – lirtosiast Jun 23 '15 at 1:04
• @ThomasKwa yep, using 0 for the end argument throws ERR:INCREMENT. You're right about not(Ans, though. – M. I. Wright Jun 23 '15 at 4:55

C++:

int reverse(int number, int number1, int number2){std::vector<int> v; v.push_back(number); v.push_back(number1); v.push_back(number2); std::cout << v << v << v; return 0;}

• Welcome to Programming Puzzles and Code Golf letsch! It is customary to include the byte count along with your submission, as this question is a code-golf. You might want to format your header as such: # C++, <number of bytes> bytes – Conor O'Brien Oct 22 '15 at 17:09
• Adding to what Conor said, you should also attempt to make your code as short as possible since this is a code golf competition. You could start by removing unnecessary whitespace and using single letter names. – Alex A. Oct 22 '15 at 18:58

Scheme, 75 characters

(string->number(list->string(reverse(string->list(number->string 76543)))))

• You can probably remove all the spaces but the last one. – Omar Nov 29 '11 at 5:50
• Count in bytes, please. – Erik the Outgolfer Apr 16 '16 at 8:03

# k3, 4 chars

0$|$

0$|$76543 \-> gives 34567


See also the K4 solution here. The only difference (saving two chars) is that 0$ converts to int. ## PHP, 37 <?function f($n){return strrev($n);}  ## C, 44 x;m(n){for(;n;x=x*10+n%10,n/=10);return x;}  • Neither of these are functions, as specified. – Kevin Reid May 1 '12 at 21:50 • @KevinReid Rectified! – l0n3sh4rk May 2 '12 at 14:47 R (35 characters) > cat(rev(strsplit("12345","")[])) 5 4 3 2 1  With help from my friends in R chat. • 12345->54321, not 12345->5 4 3 2 1. – Erik the Outgolfer Apr 16 '16 at 8:04 ## Game Maker Language, 44 Replace 12345 with whatever number or variable you want: n=12345while(n>0){r=r*10+(n mod 10)n div 10}  If you want to prompt for user input, use this 56 character long code instead: n=get_string('','')while(n>0){r=r*10+(n mod 10)n div 10}  In both pieces of code, the reverse number is stored in r • The question specifically asks for "a function (or equivalent subprogram)" which takes "a single integer valued argument". Neither of your code snippets meet that spec. – Peter Taylor Nov 30 '13 at 17:27 • @PeterTaylor They're assumed to be scripts (function equivalents). – Timtech Nov 30 '13 at 21:48 ## Haskell, 61,23 Using the string reversing technique. digitToInt is available from the Data.Char library, and of course this code would be shorter if we'd be able to assume if Data.Char already was available. -- original version 61 chars foldl1((+).(*)10).map(Data.Char.digitToInt)$reverse$show 1234 --bonus foldonly version, 67 chars foldl1((+).(*)10).foldl(flip((:).Data.Char.digitToInt))[]$show 1234

--FireFly's suggestion: 23 chars. Note that read's return type is a
-- so you might want to tack on a +1 on ghci etc so Int can be derived.
read.reverse.show$1234  • Hm, why not read it back after reversing? I.e. read.reverse.show$1234. – FireFly Dec 1 '13 at 1:19
• hmm for some silly reason I thought read had to do with IO monads. You're right, read would work. – Thom Wiggers Dec 1 '13 at 1:51
• Added it. fold was more fun though :) – Thom Wiggers Dec 1 '13 at 1:55

Groovy 32

def r(n){print ((n+"").reverse())}


# Rebol, 29

f: func[n][do reverse mold n]


Usage example in Rebol console:

>> f 76543
== 34567


If you only wanted this to work on integer input then....

f: func [n [integer!]] [do reverse mold n]


POWERSHELL, 25

-join(Read-Host)[-1..-9]


a longer version to take arbitrary input , 36

-join($a=Read-Host)[-1..-$a.length]


usage

PS C:\> -join(Read-Host)[-1..-9]
123456789
987654321
PS C:\>


# Julia, 23

r(x)=int(reverse("$x")) $ interpolates an argument (or the result of a function) into a string, denoted by the double quotes. int() automatically deletes leading zeroes.

Example:

julia> x=1234567890;r(x)
987654321


or

julia> r(1234567890)
987654321


# C# - 58

I think we need more C#

int.Parse(string.Concat(Enumerable.Reverse(x.ToString())))

• The spec requires a function or equivalent subprogram (a lambda would probably be acceptable, but a statement isn't); and it requires the return value to be similarly typed to the input (i.e. you're missing an int.Parse or a Convert.ToInt32). – Peter Taylor Jul 4 '15 at 6:39
• @CoolerRanch still a statement I think – Erik the Outgolfer Apr 16 '16 at 8:06

# ES6 Javascript, 31 bytes

x=>[...x+''].reverse().join('')

• You could save 2 bytes by using .join instead of .join(''). Also, what do you mean with that comment: "This doesn't assume b is an integer." – Stefnotch Oct 22 '15 at 17:20

# TI-BASIC, 58 54

Input N:0:While N>0:Ans+E3fpart(N,10:N/10→N:End:Ans


Usage

prgmREVERSE
?598028
820895
Done


## Burlesque, 2 bytes

Certain built-ins treat numbers as list of digits. The reverse built-in for example treats integers as a list of digits and thus reverses integers.

blsq ) 76543<-
34567


(For characters <- switches case).

# MATL, 3 bytes (non-competing)

VPU


This uses release 10.1.0 of the language/compiler, which is the current version at the time of writing.

Try it online!

### Explanation

V   % implicitly input a number and convert to string
P   % flip
U   % convert to number and implicitly display


# Python 2, 26 bytes

print int(input()[::-1])