31
4
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
31
4
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
85
‮n
replace n
with your number
1@JoeFish When I look at the comment, your username is flipped and there is some text after it. txet emos si ereH – Stefnotch – 2015-10-22T17:03:55.367
1This is just plain genius. I'd go for one char. Or 2, as it encodes to two bytes in UTF-16 :P – tomsmeding – 2012-12-03T13:33:54.217
18Hahaha I did a Google search on that tag and was rewarded with Your search -
- did not match any documents. – JoeFish – 2012-12-04T14:32:50.297
U could try this link in browser: data:text/html,&%238238;egnahcxEkcatS olleH
– F. Hauri – 2013-12-01T12:20:35.590
3
Funny in google transate too. @JoeFish: I can't reproduce, please post a link!
– F. Hauri – 2013-12-01T12:27:20.93332
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])
Work's only in Python 2 – Hauleth – 2012-03-07T20:19:58.720
It doesn't work with negative values. – elssar – 2012-03-09T10:01:50.243
This doesn't work with numbers that are longs. Example: print int(`2**32`[::-1])
– mbomb007 – 2015-06-23T20:54:35.763
4s[::-1]
is a lot faster than ''.join(reversed(s))
– riza – 2011-06-11T12:56:28.843
4You can use backticks (for repr) instead of using str – gnibbler – 2011-06-12T11:11:31.240
@gnibbler Thanks for suggestion. I've updated my answer. – Vader – 2011-06-12T13:03:42.713
2TBH, that ain't a function/proceduce/whatever you want to call it, and the specs require it. – Thomas Eding – 2011-08-19T20:39:36.790
Also, it doesn't even accept a value... – Exelian – 2011-08-30T18:43:39.290
28
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.
Not every language has a modulus operator... so it's not universal. Just an FYI. – mbomb007 – 2015-06-23T20:57:10.943
@mbomb007 that's interesting, for example? – Kiril Kirov – 2015-06-24T07:11:05.383
1
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.)
If you replace mod
with %
, it's valid Python ;) – phihag – 2011-06-11T11:02:44.200
You're right, actually :) 10x – None – 2011-06-11T11:05:01.430
But see below it is not the shortest way. – Jakob Bowyer – 2011-06-11T12:48:25.217
3Not the shortest, but the most common and universal. – Kiril Kirov – 2011-06-11T12:53:48.437
3y=y*10+x%10
.... – st0le – 2011-06-11T13:48:40.147
I prefer this to all the string methods, because it's more efficient and elegant, and some APIs may decide that the reverse of e.g. 110 ('011') is 11 octal. – Rune Aamodt – 2011-06-22T12:48:44.613
Why not use the built-in divmod()
function? You don't even have to import it. – Exelian – 2011-08-30T18:40:05.300
Because I wanted to make universal solution, that can be written in any language and I didn't want to use any built-in functions. – Kiril Kirov – 2011-08-31T07:11:26.687
13
+$n.flip
or:
$n.flip
for dynamically typed code.
Numbers got string methods due to language design.
10
".|.":y
Where y is your value.
2As a function: |.&.":
"reverse under do" which is pretty much a literal translation of the task. – FireFly – 2014-08-08T20:40:16.403
9
⍎⌽⍕
Usage:
⍎⌽⍕12345 => 54321
8
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):
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.
8
(int)strrev(123);
To do it short where N
is a constant:
strrev(N)
8
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.
3Those are the only literals, but other numbers could certainly be represented. Otherwise, the winning answer would be Brainfuck with the empty program. ;-) – FireFly – 2013-12-01T10:07:53.767
7
f=read.reverse.show.(+0)
2How about f=read.reverse.show.(+0)
? – FUZxxl – 2011-06-11T13:43:13.173
2(+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 – 2011-08-10T22:14:26.693
7
: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 – 2013-01-04T18:35:06.067
6
x = 13456
x.to_s.reverse
A number that starts with 0 doesnt seem to work. 0112.to_s.reverse.to_i => 47 – Joel – 2015-02-16T15:35:11.987
3123456.to_s.reverse is even shorter. – Steffen Roller – 2012-11-28T05:33:35.263
@mmdemirbas - thanks for fixing the typo – bodacious – 2012-11-28T15:39:43.573
3Needs to be .to_s.reverse.to_i
to comply with spec. – histocrat – 2012-12-29T16:48:05.033
@Joel A "number starting with 0", in ruby, is octal. I.e. 0112 == 74
. So unless you make a fundamental change to the ruby language, I think that's outside of scope. – Tom Lord – 2017-11-08T10:12:03.370
Also, you can shave an extra digit off, with: x.digits.join.to_i
– Tom Lord – 2017-11-08T10:12:44.187
3"no" is undefined. I think you meant to put "x" there. – David Rivers – 2011-11-29T03:59:04.680
6
Scala - 33 Chars
def r(a:Int)=(a+"").reverse.toInt
1+1 for scala, nice to see something else than python/ruby/perl – lhk – 2012-12-12T10:19:54.560
This will fail on negative Int. -123 should return -321 – samach – 2019-08-12T21:04:59.123
6
r=lambda i:int(str(i)[::-1])
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.
5
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;
}
This method overflow's on languages with limited precision. try 1111111119
– st0le – 2012-05-16T06:46:11.017
5Mine is absolutely the same (: – None – 2011-06-11T11:01:20.227
Ya, only difference is your code looks like Python. – None – 2011-06-11T11:08:35.473
5
`-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 – 2012-03-07T19:47:16.750
5
In shell scripting :
echo "your number"|rev
Hope this was useful :)
good one! didn't know bash was capable to that also! – Pranit Bauva – 2013-01-08T16:17:48.007
1I 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) – FireFly – 2013-12-01T01:26:49.840
this is invalid: 'rev' is not a builtin, but an external program call. – Bastian Bittorf – 2018-07-22T19:45:45.910
67 Bytes pure POSIX shell: X=$1;while [ $X != 0 ];do Y=$((Y*10+X%10));X=$((X/10));done;echo $Y – Bastian Bittorf – 2018-07-22T19:46:18.990
1Just 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. – nyuszika7h – 2014-07-01T20:43:39.427
3
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.
3
Kinda late but
⍎⌽⍞
If you insists on a function
⍎∘⌽∘⍕
Well looks like I couldn't spot a duplicate above...(due to it being on the 2nd page) – TwiNight – 2012-12-29T16:26:55.187
I'm sad, that nobody gave brainfu*k or whitespace solution :( (one more vote and you're on the first page ) – Kiril Kirov – 2013-11-30T11:38:40.580
@KirilKirov I've a brainfu*k solution : http://codegolf.stackexchange.com/a/32826/24829
– rpax – 2014-07-02T13:08:00.9102
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));
}
}
Will Overflow... – st0le – 2012-05-16T06:46:42.420
2It 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 – 2011-06-11T14:20:38.133
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 – 2011-06-13T07:38:31.527
2
Numbers and strings are interchangeable, so this is trivial
string.reverse(12345)
2
This one ACTUALLY takes an input, unlike some of the rest:
print`input()`[::-1]
Python btw.
2
43 characters. num as the parameter to the function:
num.toString().split('').reverse().join('')
2
r={"$it".reverse() as BigDecimal}
assert r(1234) == 4321
assert r(345678987654567898765) == 567898765456789876543
assert r(345346457.24654654) == 45645642.754643543
2
The p
flag is needed for this to work, included in the count.
Usage:
$ echo 76543 | perl -pE '$_=reverse'
I count 10 chars – F. Hauri – 2013-12-01T13:20:26.130
The p
flag is included in the count – Zaid – 2013-12-01T15:54:43.857
2
#(->> % str reverse(apply str)read-string)
Example usage:
(#(->> % str reverse(apply str)read-string) 98321)
returns 12389
2
.|$
Evaluate (.
) the reverse (|
) of casting to a string ($
).
Usage example:
.|$76543
34567
2
#
+#(.*)(.)/\2#\1
#/
Technically, this doesn't count (rs was created earlier this year), but I didn't see any other regex-based answers, and I thought this was neat.
#
Insert a pound character at the beginning of the string. This is used as a marker.
+#(.*)(.)/\2#\1
Continuously prepend the last character of the main string to the area before the marker until there are no characters left.
#/
Remove the marker.
2
$regsubex(12,/(.)/g,$mid(\A,-\n,1))
2
(first(list(parse-integer(reverse(write-to-string '4279)))))
will get you 9724.
Why (first(list
? parse-integer
already returns the number. – Florian Margaine – 2015-07-04T18:26:00.433
1
Depends on what you mean by short (javascript):
alert(String(123).split('').reverse().join('')),
this is short for sure :) – None – 2011-06-11T10:56:25.793
8alert((''+123).split('').reverse().join(''));
– st0le – 2011-06-12T02:21:47.000
1Why not alert(prompt().split('').reverse().join(''));
? – Wolle Vanillebär Lutz – 2014-07-02T10:07:33.797
1
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) );
1
int reversed = Convert.ToInt32(String.Join<char>(null, 76543.ToString().Reverse()));
int.Parse
should be shorter. – Joey – 2011-06-12T10:24:29.890
An anonymous user proposed editing this to int reversed = int.Parse(string.Join("", ("" + 76543).Reverse()));
– Peter Taylor – 2011-09-28T08:03:49.373
1
>,[>,]<[.<]
This accepts any string, not just numbers (ASCII 48-57). – Erik the Outgolfer – 2016-04-16T08:00:33.857
1
Simple:
$x=reverse (98765);
1
k4 - 6 characters
"I"$|$
Examples:
"I"$|$76543
34567
"I"$|$98765
56789
Explanation from right to left: ("I"$ = cast to integer)(| = reverse)($ = convert to string)
1
""+new StringBuilder(""+i).reverse();
1
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
1
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:
read a;sed s.^0*..\;s.0*$..<<<$a|rev
str(int(raw_input()))
really? [Python 2] [str(int(input()))
] [from your example print int(reverse(str(int(raw_input()))))
] – Erik the Outgolfer – 2016-04-16T07:58:04.920
I think right count is 3
: rev
alone will suffice – F. Hauri – 2013-12-01T13:24:28.710
“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 – 2013-12-02T09:40:09.383
1@manatwork Shorter versions: r()(rev<<<$1)
or r()(exit `rev<<<$1`)
. – jimmy23013 – 2014-07-01T21:20:44.950
Cool trick, @user23013. – manatwork – 2014-07-02T10:57:44.677
1
The existing ruby answer wasn't a function/lambda, so here goes:
f=->i{i.to_s.reverse.to_i}
1
1
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.
1Doesn'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 – 2015-06-23T01:04:05.753
@ThomasKwa yep, using 0 for the end argument throws ERR:INCREMENT. You're right about not(Ans
, though. – M. I. Wright – 2015-06-23T04:55:27.100
1
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;}
3Welcome to Programming Puzzles and Code Golf letsch! It is customary to include the byte count along with your submission, as this question is a [tag:code-golf]. You might want to format your header as such: # C++, <number of bytes> bytes
– Conor O'Brien – 2015-10-22T17:09:17.343
1Adding 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. – 2015-10-22T18:58:47.227
1
BaCon
PRINT REVERSE$(STR$(76543))
Replace 76543 with any number.
0
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 – 2013-11-30T17:27:23.927
@PeterTaylor They're assumed to be scripts (function equivalents). – Timtech – 2013-11-30T21:48:07.433
0
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
1Hm, why not read
it back after reversing? I.e. read.reverse.show$1234
. – FireFly – 2013-12-01T01:19:11.453
hmm for some silly reason I thought read had to do with IO monads. You're right, read would work. – Thom Wiggers – 2013-12-01T01:51:44.100
1Added it. fold was more fun though :) – Thom Wiggers – 2013-12-01T01:55:15.037
0
Groovy 32
def r(n){print ((n+"").reverse())}
0
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]
0
Input N:0:While N>0:Ans+E3fpart(N,10:N/10→N:End:Ans
Usage
prgmREVERSE
?598028
820895
Done
0
Scheme, 75 characters
(string->number(list->string(reverse(string->list(number->string 76543)))))
Count in bytes, please. – Erik the Outgolfer – 2016-04-16T08:03:20.590
You can probably remove all the spaces but the last one. – Omar – 2011-11-29T05:50:13.300
0
0$|$
0$|$76543 \-> gives 34567
See also the K4 solution here. The only difference (saving two chars) is that 0$
converts to int.
0
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:\>
0
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
0
I think we need more C#
int.Parse(string.Concat(Enumerable.Reverse(x.ToString())))
2The 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 – 2015-07-04T06:39:18.320
1@CoolerRanch still a statement I think – Erik the Outgolfer – 2016-04-16T08:06:34.933
0
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 – 2015-10-22T17:20:47.550
0
<?function f($n){return strrev($n);}
x;m(n){for(;n;x=x*10+n%10,n/=10);return x;}
Neither of these are functions, as specified. – Kevin Reid – 2012-05-01T21:50:48.017
@KevinReid Rectified! – l0n3sh4rk – 2012-05-02T14:47:44.280
0
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).
0
VPU
This uses release 10.1.0 of the language/compiler, which is the current version at the time of writing.
V % implicitly input a number and convert to string
P % flip
U % convert to number and implicitly display
0
print int(`input()`[::-1])
0
I decided to make a function instead of hardcoding it.
def r(n):print(int(str(n)[::-1]))
The code is pretty self-explanatory.
Usage: r(12345)
0
SELECT 0+REVERSE(:1||'')FROM DUAL;
0
R (35 characters)
> cat(rev(strsplit("12345","")[[1]]))
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 – 2016-04-16T08:04:10.983
-1
a=b=>b.split("").reverse().join("")
This doesn't assume b
is an integer. – Afonso Matos – 2015-07-04T18:54:28.270
-1
Replace n with your number
([]+n).split("").reverse().join("")
This is a block of code. OP says function or similar. – Afonso Matos – 2015-07-04T18:55:13.730
2The brief says you have to have your code accept a number, this just looks like a snippet of code... – WallyWest – 2014-09-04T23:16:48.513
The algorithm for palindromic numbers needs at least one time step to output the number ;) – M L – 2015-07-04T17:22:38.977
6Go back to the time the number was a string, then reverse the string – pmg – 2011-06-11T10:54:17.213
2The 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 ... – None – 2011-06-11T10:56:36.090
3Just a notice: any number ending with 0 becomes a shorter number of digits when reversed... – powtac – 2011-06-11T12:44:40.373
44I know an algorithm that takes no time at all, but only works on palindromic numbers ;) – schnaader – 2011-06-11T14:47:14.047
Found time to do the re-write myself. I hope this remain the puzzle that eltond meant to pose. – dmckee --- ex-moderator kitten – 2011-06-12T00:37:14.633