# 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

-
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

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

``````&#8238;n
``````

replace `n` with your number

-
This is just plain genius. I'd go for one char. Or 2, as it encodes to two bytes in UTF-16 :P – tomsmeding Dec 3 '12 at 13:33
Hahaha I did a Google search on that tag and was rewarded with `Your search -‮ `- did not match any documents. – JoeFish Dec 4 '12 at 14:32

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])
``````
-
`s[::-1]` is a lot faster than `''.join(reversed(s))` – riza Jun 11 '11 at 12:56
You can use backticks (for repr) instead of using str – gnibbler Jun 12 '11 at 11:11
@gnibbler Thanks for suggestion. I've updated my answer. – Vader Jun 12 '11 at 13:03
TBH, that ain't a function/proceduce/whatever you want to call it, and the specs require it. – Thomas Eding Aug 19 '11 at 20:39
Also, it doesn't even accept a value... – Exelian Aug 30 '11 at 18:43

If you want to use only numbers (not convert it to string), and don't want to use some specific library (to be universal for any language), I'd do it like this

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

-
If you replace `mod` with `%`, it's valid Python ;) – phihag Jun 11 '11 at 11:02
You're right, actually :) 10x – Kiril Kirov Jun 11 '11 at 11:05
But see below it is not the shortest way. – Jakob Bowyer Jun 11 '11 at 12:48
Not the shortest, but the most common and universal. – Kiril Kirov Jun 11 '11 at 12:53
`y=y*10+x%10`.... – st0le Jun 11 '11 at 13:48

## Perl 6

``````+\$n.flip
``````

or:

``````\$n.flip
``````

for dynamically typed code.

Numbers got string methods due to language design.

-

``````f=read.reverse.show.(+0)
``````
-
How about `f=read.reverse.show.(+0)`? – FUZxxl Jun 11 '11 at 13:43
`(+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. – Thomas Eding Aug 10 '11 at 22:14

# PHP, 9 chars

``````(int)strrev(123);
``````

To do it short where `N` is a constant:

``````strrev(N)
``````
-

# J - 6 characters + variable

``````".|.":y
``````

-

# Ruby (14)

``````x = 13456
x.to_s.reverse
``````
-
"no" is undefined. I think you meant to put "x" there. – David Rivers Nov 29 '11 at 3:59
123456.to_s.reverse is even shorter. – Steffen Roller Nov 28 '12 at 5:33
@mmdemirbas - thanks for fixing the typo – bodacious Nov 28 '12 at 15:39
Needs to be `.to_s.reverse.to_i` to comply with spec. – histocrat Dec 29 '12 at 16:48

Python:

``````int(''.join(reversed(str(1234))))
``````
-
 I was just about to write this when I saw you had posted it. +1 – Jakob Bowyer Jun 11 '11 at 11:50

# Vim

17 chars

``````:se ri<CR>C<C-R>"
``````
-
 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 :) – Daniero Jan 4 at 18:35

## 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
``````
-
 I think you must've meant ``-1%~` rather than ``-1\$~` (and I've taken the liberty of editing your answer to say so). – Ilmari Karonen Mar 7 '12 at 19:47

In shell scripting :

``````  echo "your number"|rev
``````

Hope this was useful :)

-
 good one! didn't know bash was capable to that also! – Pranit Bauva Jan 8 at 16:17

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;
}
``````
-
Mine is absolutely the same (: – Kiril Kirov Jun 11 '11 at 11:01
Ya, only difference is your code looks like Python. – taskinoor Jun 11 '11 at 11:08
This method overflow's on languages with limited precision. try `1111111119` – st0le May 16 '12 at 6:46

Scala - 33 Chars

``````def r(a:Int)=(a+"").reverse.toInt
``````
-
 +1 for scala, nice to see something else than python/ruby/perl – lhk Dec 12 '12 at 10:19

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));
}
}
``````
-
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. – R. Martinho Fernandes Jun 11 '11 at 14:20
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. – Victor Jun 13 '11 at 7:38
Will Overflow... – st0le May 16 '12 at 6:46

You can use reversing a String in Java

``````long l =
long reversed = Long.parseLong(new StringBuilder().append(l).reverse().toString());
``````
-
Which language are you using here? – FUZxxl Jun 13 '11 at 10:16
The original question was tagged `Java` – Peter Lawrey Jun 13 '11 at 10:54
Will Overflow...Use `BigInteger` – st0le May 16 '12 at 6:46

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

-
+1, I totally agree, hardcode is for wusses. – Exelian Aug 30 '11 at 18:45

# Lua

Numbers and strings are interchangeable, so this is trivial

``````string.reverse(12345)
``````
-

## Actionscript

43 characters. num as the parameter to the function:

``````num.toString().split('').reverse().join('')
``````
-

# Java

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

# Groovy

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

assert r(1234) == 4321
assert r(345678987654567898765) == 567898765456789876543
assert r(345346457.24654654) == 45645642.754643543
``````
-

# Perl, 11 chars

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

Usage:

``````\$ echo 76543 | perl -pE '\$_=reverse'
``````
-

# Clojure (42 chars)

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

Example usage:

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

returns 12389

-

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

-

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('') ) );
}

``````
-

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

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

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

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

Python btw.

-

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);`

-