31
\$\begingroup\$

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

\$\endgroup\$
  • 6
    \$\begingroup\$ Go back to the time the number was a string, then reverse the string \$\endgroup\$ – pmg Jun 11 '11 at 10:54
  • 2
    \$\begingroup\$ 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 ... \$\endgroup\$ – Pointy Jun 11 '11 at 10:56
  • 3
    \$\begingroup\$ Just a notice: any number ending with 0 becomes a shorter number of digits when reversed... \$\endgroup\$ – powtac Jun 11 '11 at 12:44
  • 44
    \$\begingroup\$ I know an algorithm that takes no time at all, but only works on palindromic numbers ;) \$\endgroup\$ – schnaader Jun 11 '11 at 14:47
  • \$\begingroup\$ Found time to do the re-write myself. I hope this remain the puzzle that eltond meant to pose. \$\endgroup\$ – dmckee Jun 12 '11 at 0:37

64 Answers 64

1
\$\begingroup\$

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) );
\$\endgroup\$
1
\$\begingroup\$

Depends on what you mean by short (javascript):

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

C#

int reversed = Convert.ToInt32(String.Join<char>(null, 76543.ToString().Reverse()));
\$\endgroup\$
  • \$\begingroup\$ int.Parse should be shorter. \$\endgroup\$ – Joey Jun 12 '11 at 10:24
  • \$\begingroup\$ An anonymous user proposed editing this to int reversed = int.Parse(string.Join("", ("" + 76543).Reverse())); \$\endgroup\$ – Peter Taylor Sep 28 '11 at 8:03
1
\$\begingroup\$

k4 - 6 characters

"I"$|$

Examples:

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

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

\$\endgroup\$
1
\$\begingroup\$

Perl (19 chars)

Simple:

$x=reverse (98765);

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ I think right count is 3: rev alone will suffice \$\endgroup\$ – F. Hauri Dec 1 '13 at 13:24
  • \$\begingroup\$ “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`;}.) \$\endgroup\$ – manatwork Dec 2 '13 at 9:40
  • 1
    \$\begingroup\$ @manatwork Shorter versions: r()(rev<<<$1) or r()(exit `rev<<<$1`). \$\endgroup\$ – jimmy23013 Jul 1 '14 at 21:20
  • \$\begingroup\$ Cool trick, @user23013. \$\endgroup\$ – manatwork Jul 2 '14 at 10:57
  • \$\begingroup\$ str(int(raw_input())) really? [Python 2] [str(int(input()))] [from your example print int(reverse(str(int(raw_input()))))] \$\endgroup\$ – Erik the Outgolfer Apr 16 '16 at 7:58
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

ruby (26)

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

f=->i{i.to_s.reverse.to_i}
\$\endgroup\$
1
\$\begingroup\$

BaCon

PRINT REVERSE$(STR$(76543))

Replace 76543 with any number.

\$\endgroup\$
1
\$\begingroup\$

Java

""+new StringBuilder(""+i).reverse();
\$\endgroup\$
1
\$\begingroup\$

Brainfuck, 11

>,[>,]<[.<]
\$\endgroup\$
  • \$\begingroup\$ This accepts any string, not just numbers (ASCII 48-57). \$\endgroup\$ – Erik the Outgolfer Apr 16 '16 at 8:00
1
\$\begingroup\$

Pyth (3 chars)

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

Try it here

v_z
\$\endgroup\$
1
\$\begingroup\$

TI-BASIC, 35 32 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.

\$\endgroup\$
  • 1
    \$\begingroup\$ 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! \$\endgroup\$ – lirtosiast Jun 23 '15 at 1:04
  • \$\begingroup\$ @ThomasKwa yep, using 0 for the end argument throws ERR:INCREMENT. You're right about not(Ans, though. \$\endgroup\$ – M. I. Wright Jun 23 '15 at 4:55
1
\$\begingroup\$

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[2] << v[1] << v[0]; return 0;}
\$\endgroup\$
  • 3
    \$\begingroup\$ 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 \$\endgroup\$ – Conor O'Brien Oct 22 '15 at 17:09
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Alex A. Oct 22 '15 at 18:58
0
\$\begingroup\$

Scheme, 75 characters

(string->number(list->string(reverse(string->list(number->string 76543)))))
\$\endgroup\$
  • \$\begingroup\$ You can probably remove all the spaces but the last one. \$\endgroup\$ – Omar Nov 29 '11 at 5:50
  • \$\begingroup\$ Count in bytes, please. \$\endgroup\$ – Erik the Outgolfer Apr 16 '16 at 8:03
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

PHP, 37

<?function f($n){return strrev($n);}

C, 44

x;m(n){for(;n;x=x*10+n%10,n/=10);return x;}
\$\endgroup\$
  • \$\begingroup\$ Neither of these are functions, as specified. \$\endgroup\$ – Kevin Reid May 1 '12 at 21:50
  • \$\begingroup\$ @KevinReid Rectified! \$\endgroup\$ – l0n3sh4rk May 2 '12 at 14:47
0
\$\begingroup\$

R (35 characters)

> cat(rev(strsplit("12345","")[[1]]))
5 4 3 2 1

With help from my friends in R chat.

\$\endgroup\$
  • \$\begingroup\$ 12345->54321, not 12345->5 4 3 2 1. \$\endgroup\$ – Erik the Outgolfer Apr 16 '16 at 8:04
0
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Peter Taylor Nov 30 '13 at 17:27
  • \$\begingroup\$ @PeterTaylor They're assumed to be scripts (function equivalents). \$\endgroup\$ – Timtech Nov 30 '13 at 21:48
0
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ Hm, why not read it back after reversing? I.e. read.reverse.show$1234. \$\endgroup\$ – FireFly Dec 1 '13 at 1:19
  • \$\begingroup\$ hmm for some silly reason I thought read had to do with IO monads. You're right, read would work. \$\endgroup\$ – Thom Wiggers Dec 1 '13 at 1:51
  • 1
    \$\begingroup\$ Added it. fold was more fun though :) \$\endgroup\$ – Thom Wiggers Dec 1 '13 at 1:55
0
\$\begingroup\$

Groovy 32

def r(n){print ((n+"").reverse())}
\$\endgroup\$
0
\$\begingroup\$

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]
\$\endgroup\$
0
\$\begingroup\$

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:\>
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

C# - 58

I think we need more C#

int.Parse(string.Concat(Enumerable.Reverse(x.ToString())))
\$\endgroup\$
  • 2
    \$\begingroup\$ 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). \$\endgroup\$ – Peter Taylor Jul 4 '15 at 6:39
  • 1
    \$\begingroup\$ @CoolerRanch still a statement I think \$\endgroup\$ – Erik the Outgolfer Apr 16 '16 at 8:06
0
\$\begingroup\$

ES6 Javascript, 31 bytes

x=>[...x+''].reverse().join('')
\$\endgroup\$
  • \$\begingroup\$ 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." \$\endgroup\$ – Stefnotch Oct 22 '15 at 17:20
0
\$\begingroup\$

TI-BASIC, 58 54

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

Usage

prgmREVERSE
?598028
          820895
            Done
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Python 2, 26 bytes

print int(`input()`[::-1])
\$\endgroup\$