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

63 Answers 63

86
\$\begingroup\$

HTML 21 7 chars (1 char if I'm cheeky...)

‮n

replace n with your number

\$\endgroup\$
5
  • 2
    \$\begingroup\$ This is just plain genius. I'd go for one char. Or 2, as it encodes to two bytes in UTF-16 :P \$\endgroup\$
    – tomsmeding
    Commented Dec 3, 2012 at 13:33
  • 18
    \$\begingroup\$ Hahaha I did a Google search on that tag and was rewarded with Your search -‮ - did not match any documents. \$\endgroup\$
    – JoeFish
    Commented Dec 4, 2012 at 14:32
  • \$\begingroup\$ U could try this link in browser: data:text/html,&%238238;egnahcxEkcatS olleH \$\endgroup\$ Commented Dec 1, 2013 at 12:20
  • 3
    \$\begingroup\$ Funny in google transate too. @JoeFish: I can't reproduce, please post a link! ‮ \$\endgroup\$ Commented Dec 1, 2013 at 12:27
  • 1
    \$\begingroup\$ @JoeFish When I look at the comment, your username is flipped and there is some text after it. ‮txet emos si ereH \$\endgroup\$
    – Stefnotch
    Commented Oct 22, 2015 at 17:03
33
\$\begingroup\$

Python

int(str(76543)[::-1])

EDIT:

Shorter solution as suggested by @gnibbler:

int(`76543`[::-1])

or, if above is unclear:

x=76543
int(`x`[::-1])
\$\endgroup\$
8
  • 4
    \$\begingroup\$ s[::-1] is a lot faster than ''.join(reversed(s)) \$\endgroup\$
    – riza
    Commented Jun 11, 2011 at 12:56
  • 4
    \$\begingroup\$ You can use backticks (for repr) instead of using str \$\endgroup\$
    – gnibbler
    Commented Jun 12, 2011 at 11:11
  • \$\begingroup\$ @gnibbler Thanks for suggestion. I've updated my answer. \$\endgroup\$
    – Vader
    Commented Jun 12, 2011 at 13:03
  • 2
    \$\begingroup\$ TBH, that ain't a function/proceduce/whatever you want to call it, and the specs require it. \$\endgroup\$ Commented Aug 19, 2011 at 20:39
  • \$\begingroup\$ Also, it doesn't even accept a value... \$\endgroup\$
    – Exelian
    Commented Aug 30, 2011 at 18:43
28
\$\begingroup\$

Universal (language agnostic/independent)

If you want to use only numbers (avoid converting the number to string) and don't want to use some specific library (to be universal for any language):

x = 76543 # or whatever is your number
y = 0
while x > 0:
    y *= 10
    y += ( x %10 )
    x /= 10 # int division 

This is python, but it could be done in any language, because it's just a math method.

\$\endgroup\$
11
  • \$\begingroup\$ If you replace mod with %, it's valid Python ;) \$\endgroup\$
    – phihag
    Commented Jun 11, 2011 at 11:02
  • \$\begingroup\$ You're right, actually :) 10x \$\endgroup\$
    – Kiril Kirov
    Commented Jun 11, 2011 at 11:05
  • 3
    \$\begingroup\$ Not the shortest, but the most common and universal. \$\endgroup\$ Commented Jun 11, 2011 at 12:53
  • 3
    \$\begingroup\$ y=y*10+x%10.... \$\endgroup\$
    – st0le
    Commented Jun 11, 2011 at 13:48
  • 1
    \$\begingroup\$ BrainFuck doesn't, though it can be calculated. Any language that doesn't have it can use a - (n * int(a/n)) instead of a mod n. Also, if you look here, the modulus operation is implemented differently in every language. (See the table on the right.) \$\endgroup\$
    – mbomb007
    Commented Jun 24, 2015 at 14:25
13
\$\begingroup\$

Perl 6

+$n.flip

or:

$n.flip

for dynamically typed code.

Numbers got string methods due to language design.

\$\endgroup\$
10
\$\begingroup\$

J - 6 characters + variable

".|.":y

Where y is your value.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ As a function: |.&.": "reverse under do" which is pretty much a literal translation of the task. \$\endgroup\$
    – FireFly
    Commented Aug 8, 2014 at 20:40
10
\$\begingroup\$

APL (3)

⍎⌽⍕

Usage:

⍎⌽⍕12345 => 54321
\$\endgroup\$
8
\$\begingroup\$

Vim

17 chars

:se ri<CR>C<C-R>"
\$\endgroup\$
1
  • \$\begingroup\$ I would say that's 10 chars (keystrokes) if you type the command directly in vim. Btw, I learned something new in vim today, thanks :) \$\endgroup\$
    – daniero
    Commented Jan 4, 2013 at 18:35
8
\$\begingroup\$

PHP, 9 chars

(int)strrev(123);

To do it short where N is a constant:

strrev(N)
\$\endgroup\$
8
\$\begingroup\$

Befunge (3 characters)

Complete runnable program:

N.@

Where N is your number. Rules say "accept a single integer valued argument"; In Befunge you can only enter integers from 0 to 9.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Those are the only literals, but other numbers could certainly be represented. Otherwise, the winning answer would be Brainfuck with the empty program. ;-) \$\endgroup\$
    – FireFly
    Commented Dec 1, 2013 at 10:07
8
\$\begingroup\$

Language-independent/mathematics

Inspired by Kiril Kirov's answer above. I got curious about the mathematical properties of reversing a number, so I decided to investigate a bit.

Turns out if you plot the difference n - rev(n) for natural numbers n in some base r, you get patterns like this ((n - rev(n)) / (r - 1), for r=10, wrapped at r columns, red denotes negative number):

table of differences

This sequence could be generated as such (pseudocode):

for i=1 to r:
  output 0

for m=0, 1, …
  for k=1 to (r-1):
    for d=1 to r^m:
      for i=0 to (r-1):
        output (r-1) * (r+1)^m * (k - i)

If you store these values in a list/array, then n - arr[n] would get you the reversed form of n. Now, to "mathematically golf" this, we'd ideally want a closed-form expression that gives us the n:th value in the sequence, so that we could have a closed-form expression for solving the entire task. Unfortunately, I haven't been able to find such an expression... but it looks like it should be possible. :(

So yeah, not so much a code-golf as a mathematical curiosity, but if there is a closed-form expression of the above sequence it might actually be useful in proper PL golf submissions.

\$\endgroup\$
7
\$\begingroup\$

Haskell, 28 24 characters

f=read.reverse.show.(+0)
\$\endgroup\$
2
  • 2
    \$\begingroup\$ How about f=read.reverse.show.(+0)? \$\endgroup\$
    – FUZxxl
    Commented Jun 11, 2011 at 13:43
  • 2
    \$\begingroup\$ (+0): Legit man! Though technically you don't need the .(+0) at all, as f would be more polymorphic than what the problem requires (it is allowed to return a 'similarly typed' output). I would shave off those 5 characters. \$\endgroup\$ Commented Aug 10, 2011 at 22:14
6
\$\begingroup\$

Scala - 33 Chars

def r(a:Int)=(a+"").reverse.toInt
\$\endgroup\$
2
  • 1
    \$\begingroup\$ +1 for scala, nice to see something else than python/ruby/perl \$\endgroup\$
    – lhk
    Commented Dec 12, 2012 at 10:19
  • \$\begingroup\$ This will fail on negative Int. -123 should return -321 \$\endgroup\$
    – samach
    Commented Aug 12, 2019 at 21:04
6
\$\begingroup\$

Python 3+

Function form: 28 characters

r=lambda i:int(str(i)[::-1])

(Sub)program form: 25 characters

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

I consider some of the other Python examples to be cheating, or at least cheap, due to using hardcoded input and/or not fully satisfying the requirements.

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

Ruby (14)

x = 13456
x.to_s.reverse
\$\endgroup\$
7
  • 3
    \$\begingroup\$ "no" is undefined. I think you meant to put "x" there. \$\endgroup\$ Commented Nov 29, 2011 at 3:59
  • 3
    \$\begingroup\$ 123456.to_s.reverse is even shorter. \$\endgroup\$ Commented Nov 28, 2012 at 5:33
  • \$\begingroup\$ @mmdemirbas - thanks for fixing the typo \$\endgroup\$
    – bodacious
    Commented Nov 28, 2012 at 15:39
  • 3
    \$\begingroup\$ Needs to be .to_s.reverse.to_i to comply with spec. \$\endgroup\$
    – histocrat
    Commented Dec 29, 2012 at 16:48
  • \$\begingroup\$ A number that starts with 0 doesnt seem to work. 0112.to_s.reverse.to_i => 47 \$\endgroup\$
    – Joel
    Commented Feb 16, 2015 at 15:35
5
\$\begingroup\$

It is possible to convert a number a string, then reverse the string and then convert that string back to number. This kind of feature is probably available in all language. If you are looking for a more mathematical method then this might help:

int n = 76543;
int r = 0;

while (n > 0) {
    r *= 10;
    r += n % 10;
    n /= 10;
}
\$\endgroup\$
3
  • 5
    \$\begingroup\$ Mine is absolutely the same (: \$\endgroup\$
    – Kiril Kirov
    Commented Jun 11, 2011 at 11:01
  • \$\begingroup\$ Ya, only difference is your code looks like Python. \$\endgroup\$
    – taskinoor
    Commented Jun 11, 2011 at 11:08
  • \$\begingroup\$ This method overflow's on languages with limited precision. try 1111111119 \$\endgroup\$
    – st0le
    Commented May 16, 2012 at 6:46
5
\$\begingroup\$

Golfscript, 5 chars

`-1%~

This takes an argument on the stack and leaves the result on the stack. I'm exploiting the "subprogram" option in the spec: if you insist on a function, that's four chars more leaving it on the stack:

{`-1%~}:r
\$\endgroup\$
1
  • \$\begingroup\$ I think you must've meant `-1%~ rather than `-1$~ (and I've taken the liberty of editing your answer to say so). \$\endgroup\$ Commented Mar 7, 2012 at 19:47
5
\$\begingroup\$

In shell scripting :

  echo "your number"|rev

Hope this was useful :)

\$\endgroup\$
5
  • \$\begingroup\$ good one! didn't know bash was capable to that also! \$\endgroup\$ Commented Jan 8, 2013 at 16:17
  • 1
    \$\begingroup\$ I guess technically it does return a similarly-typed "number"... could be shortened further with rev<<<yournumber, e.g. rev<<<132 (for bash/zsh, not per POSIX though) \$\endgroup\$
    – FireFly
    Commented Dec 1, 2013 at 1:26
  • 1
    \$\begingroup\$ Just rev is enough, the question doesn't say it has to be a function. You could compare rev to a built-in function, even though it's not one. \$\endgroup\$
    – user344
    Commented Jul 1, 2014 at 20:43
  • \$\begingroup\$ this is invalid: 'rev' is not a builtin, but an external program call. \$\endgroup\$ Commented Jul 22, 2018 at 19:45
  • \$\begingroup\$ 67 Bytes pure POSIX shell: X=$1;while [ $X != 0 ];do Y=$((Y*10+X%10));X=$((X/10));done;echo $Y \$\endgroup\$ Commented Jul 22, 2018 at 19:46
3
\$\begingroup\$

Kinda late but

APL, 3

⍎⌽⍞

If you insists on a function

⍎∘⌽∘⍕
\$\endgroup\$
3
  • \$\begingroup\$ Well looks like I couldn't spot a duplicate above...(due to it being on the 2nd page) \$\endgroup\$
    – TwiN
    Commented Dec 29, 2012 at 16:26
  • \$\begingroup\$ I'm sad, that nobody gave brainfu*k or whitespace solution :( (one more vote and you're on the first page ) \$\endgroup\$ Commented Nov 30, 2013 at 11:38
  • \$\begingroup\$ @KirilKirov I've a brainfu*k solution : codegolf.stackexchange.com/a/32826/24829 \$\endgroup\$
    – rpax
    Commented Jul 2, 2014 at 13:08
3
\$\begingroup\$

Mathematica, 14 bytes

IntegerReverse

This is not competing, because this function was only added in last week's 10.3 release, but for completeness I thought I'd add the only ever (I think?) built-in for this task.

\$\endgroup\$
3
\$\begingroup\$

mIRC 4.45 (35 Bytes)

$regsubex(12,/(.)/g,$mid(\A,-\n,1))
\$\endgroup\$
2
\$\begingroup\$

You could do the following in Java. Note that this converts to String and back and is not a mathematical solution.

public class test {
    public static int reverseInt(int i) {
        return Integer.valueOf((new StringBuffer(String.valueOf(i))).reverse().toString());
    }

    public static void main(String[] args) {
        int i = 1234;
        System.out.println("reverse("+i+") -> " + reverseInt(i));
    }
}
\$\endgroup\$
3
  • 2
    \$\begingroup\$ It is a mathematical solution. Mathematics is not numbers is not arithmetics. Mathematics also deals with strings of symbols. And in this special case, the conversion to and from string is just conversion to and from base-10. \$\endgroup\$ Commented Jun 11, 2011 at 14:20
  • \$\begingroup\$ What I meant by "not a mathematical solution" is that we're not doing any math ourselves. The methods are doing all of the parsing and mathematics for us. As opposed to e.g. Kiril Kirov's answer. \$\endgroup\$
    – Victor
    Commented Jun 13, 2011 at 7:38
  • \$\begingroup\$ Will Overflow... \$\endgroup\$
    – st0le
    Commented May 16, 2012 at 6:46
2
\$\begingroup\$

Depends on what you mean by short (javascript):

alert(String(123).split('').reverse().join('')),
\$\endgroup\$
3
  • \$\begingroup\$ this is short for sure :) \$\endgroup\$
    – eltond
    Commented Jun 11, 2011 at 10:56
  • 9
    \$\begingroup\$ alert((''+123).split('').reverse().join('')); \$\endgroup\$
    – st0le
    Commented Jun 12, 2011 at 2:21
  • 1
    \$\begingroup\$ Why not alert(prompt().split('').reverse().join('')); ? \$\endgroup\$
    – ˈvɔlə
    Commented Jul 2, 2014 at 10:07
2
\$\begingroup\$

Lua

Numbers and strings are interchangeable, so this is trivial

string.reverse(12345)
\$\endgroup\$
2
\$\begingroup\$

This one ACTUALLY takes an input, unlike some of the rest:

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

Python btw.

\$\endgroup\$
2
\$\begingroup\$

Actionscript

43 characters. num as the parameter to the function:

num.toString().split('').reverse().join('')
\$\endgroup\$
2
\$\begingroup\$

Groovy

r={"$it".reverse() as BigDecimal}

assert r(1234) == 4321
assert r(345678987654567898765) == 567898765456789876543
assert r(345346457.24654654) == 45645642.754643543
\$\endgroup\$
2
\$\begingroup\$

Perl, 11 chars

The p flag is needed for this to work, included in the count.

Usage:

$ echo 76543 | perl -pE '$_=reverse'
\$\endgroup\$
2
  • \$\begingroup\$ I count 10 chars \$\endgroup\$ Commented Dec 1, 2013 at 13:20
  • \$\begingroup\$ The p flag is included in the count \$\endgroup\$
    – Zaid
    Commented Dec 1, 2013 at 15:54
2
\$\begingroup\$

Clojure (42 chars)

#(->> % str reverse(apply str)read-string)

Example usage:

(#(->> % str reverse(apply str)read-string) 98321)

returns 12389

\$\endgroup\$
2
\$\begingroup\$

Common Lisp - 60 chars

(first(list(parse-integer(reverse(write-to-string '4279)))))

will get you 9724.

\$\endgroup\$
1
  • \$\begingroup\$ Why (first(list? parse-integer already returns the number. \$\endgroup\$ Commented Jul 4, 2015 at 18:26
2
\$\begingroup\$

BaCon

PRINT REVERSE$(STR$(76543))

Replace 76543 with any number.

\$\endgroup\$