Most creative way to reverse a positive integer [closed]

Provided an input as an unsigned integer:

13457


75431


Since this is a popularity contest, be creative. Creative solutions use unusual or clever techniques to accomplish given task.

Constraints:

• You cannot use arrays.
• You cannot use strings.
• No RTL Override (&#8238)

Brownie points for using creative arithmetics.

Since this is a popularity contest, I suggest not using the modulo (%) operator in your code.

If the input is:

12340


Then the output:

4321


would be acceptable.

closed as off-topic by Mego♦, cat, mbomb007, Blue, Martin EnderApr 22 '16 at 16:57

This question appears to be off-topic. The users who voted to close gave this specific reason:

• "Questions without an objective primary winning criterion are off-topic, as they make it impossible to indisputably decide which entry should win." – Mego, cat, mbomb007, Blue, Martin Ender
If this question can be reworded to fit the rules in the help center, please edit the question.

• Is it a duplicate of codegolf.stackexchange.com/questions/2823/… ? – microbian Mar 3 '14 at 18:02
• @microbian No, that one was code-golf. This one is popularity-contest. – Victor Stafusa Mar 3 '14 at 18:03
• People will be ticked if you start changing rules now. It seems to be going fine to me, just run your next challenge through the sandbox first: meta.codegolf.stackexchange.com/questions/1117/… – 23fc9a62-56de-47fb-97b4-737890 Mar 3 '14 at 18:29
• What if 1230 is the input? Are we allowed to output 321? (Otherwise, Strings are necessary). – Justin Mar 3 '14 at 18:34
• I'm voting to close this as off-topic because this lacks an objective validity criterion - "be creative" is subjective. – Mego Apr 22 '16 at 7:58

Mathematica, no modulo!

n = 14627;
length = Ceiling[Log[10, n]];
img = Rasterize[n, RasterSize -> 400, ImageSize -> 400];
box = Rasterize[n, "BoundingBox", RasterSize -> 400, ImageSize -> 400];
width = box[[1]]; height = box[[3]];
ToExpression[
TextRecognize[
ImageAssemble[
ImageTake[img, {1, height}, #] & /@
NestList[# - width/length &, {width - width/length, width},
length - 1]]]]


Let's break it down.

First we use some "creative arithmetics" to find out how many digits are in the number: length = Ceiling[Log[10, n]];

Next, we Rasterize the number to a nice large image:

Now we query for the bounding box of that image, and populate the width and height (actually using the baseline offset instead of the image height, because MM adds some whitespace below the baseline in the image).

Next, NestList recursively subtracts the width of the image divided by the length of the string to enable ImageTake to pluck characters from the end of the image one by one, and those are reassembled by ImageAssemble to this image:

Then we pass that on to the TextRecognize function for optical character recognition, which at this image size and rasterization quality is able to impeccably recognize the final output and give us the integer:

72641


Logarithms and OCR - It's like chocolate and peanut butter!

New and improved

This version pads out the number to deal with the obstinate behavior of TextRecognize with small numbers, and then subtracts out the pad at the end. This even works for single-digit numbers!

Though, why you would run a reverse routine on a single number is a mystery to me. But just for the sake of completeness, I even made it work for inputs of zero and one, which would normally break because the floored log doesn't return 1 for them.

n = 1;
length = If[n == 1 || n == 0, 1, Ceiling[Log[10, n]]];
img = Rasterize[n + (pad*10^length), RasterSize -> 400,
ImageSize -> 400];
box = ImageDimensions[img];
width = box[[1]]; height = box[[2]];
reversed =
ImageResize[
ImageAssemble[
ImageTake[img, {1, height}, #] & /@
recognized = ToExpression[TextRecognize[reversed]];

• Beat me to it. You've got my vote!! [but I was going to use C#] – HL-SDK Mar 4 '14 at 2:49
• TextRegognize isn't working for small numbers. And you have typo in height = b[[3]];. Also check my answer too, please! :) – swish Mar 4 '14 at 3:50
• Another problem with TextRecognize, is that it returns a String, which isn't allowed and also you need to convert it back to number. – swish Mar 4 '14 at 4:02
• Thanks for spotting the typo...I was making the variable names more reader friendly before submitting and missed one. Also threw in the missing ToExpression. And I posted a revision that deals with the small numbers problem all the way to single digits. – Jonathan Van Matre Mar 4 '14 at 5:24
• Wow… that's elaborate! – duci9y Mar 4 '14 at 6:29

Perl/LuaTeX/Tesseract

The following Perl script reads the number as command line argument, e.g.:

1234567890

The following Perl script prints the number via LuaTeX. A virtual font is created on the fly that mirrors the digits horizontally.

Then the whole number is again mirrored horizontally:

The final image is reread via OCR (tesseract):

0987654321

#!/usr/bin/env perl
use strict;
$^W=1; # Get the number as program argument or use a fixed number with all digits.$_ = shift // 1234567890;

$\="\n"; # append EOL, when printing # Catch negative number exit print "NaUI (Not an Unsigned Integer)" if$_ < 0;

# Catch number with one digit.
exit ! print if ($_ =$= = $_) < 10; undef$\;

# Write TeX file for LuaTeX
open(OUT, '>', 'temp.tex') or die "!!! Error: Cannot write: $!\n"; print OUT<<"END_PRINT"; % Catcode setting for iniTeX (a TeX format is not needed) \\catcode\{=1 \\catcode\}=2 \\def\\mynumber{$_}
END_PRINT
print OUT<<'END_PRINT';
\directlua{tex.enableprimitives('',tex.extraprimitives())}
\pdfoutput=1 % PDF output
% move origin to (0,0)
\pdfhorigin=0bp
\pdfvorigin=0bp
% magnify the result by 5
\mag=5000

% Create virtual font, where the digits are mirrored
\directlua{
callback.register('define_font',
function (name,size)
if name == 'cmtt10-digits' then
f.name = 'cmtt10-digits'
f.type = 'virtual'
f.fonts = {{ name = 'cmtt10', size = size }}
for i,v in pairs(f.characters) do
if (string.char(i)):find('[1234567890]') then
v.commands = {
{'right',f.characters[i].width},
{'special','pdf: q -1 0 0 1 0 0 cm'},
{'char',i},
{'right',-f.characters[i].width},
{'special','pdf: Q'},
}
else
v.commands = {{'char',i}}
end
end
else
end
return f
end
)
}

% Activate the new font
\font\myfont=cmtt10-digits\relax
\myfont

% Put the number in a box and add a margin (for tesseract)
\dimen0=5bp % margin
\setbox0=\hbox{\kern\dimen0 \mynumber\kern\dimen0}
\ht0=\dimexpr\ht0+\dimen0\relax
\dp0=\dimexpr\dp0+\dimen0\relax
\pdfpagewidth=\wd0
\pdfpageheight=\dimexpr\ht0+\dp0\relax

% For illustration only: Print the number with the reflected digits:
\shipout\copy0 % print the number with the reflected digits

% Final version on page 2: Print the box with the number, again mirrored
\shipout\hbox{%
\kern\wd0
\pdfliteral{q -1 0 0 1 0 0 cm}%
\copy0
\pdfliteral{Q}%
}

% End job, no matter, whether iniTeX, plain TeX or LaTeX
\csname @@end\endcsname\end
END_PRINT

system "luatex --ini temp.tex >/dev/null";
system qw[convert temp.pdf temp%d.png];
system "tesseract temp1.png temp >/dev/null 2>&1";

# debug versions with output on console
#system "luatex --ini temp.tex";
#system qw[convert temp.pdf temp%d.png];
#system "tesseract temp1.png temp";

# Output the result, remove empty lines
open(IN, '<', 'temp.txt') or die "!!! Error: Cannot open: $!\n"; chomp, print while <IN>; print "\n"; close(IN); __END__  • +1 for TeX. We need more TeX answers! – Jonathan Van Matre Mar 5 '14 at 15:54 Brainfuck Basically, it is just an input-reversing program. ,[>,]<[.<]  UPD: As Sylwester pointed out in comments, in the classical Brainfuck interpreters/compilers (without possibility to going left from zero point in the memory array) this program would not work in the absence of '>' at the beginning, so the more stable version is: >,[>,]<[.<]  • Shortest Bf program I've ever seen. Also, really neat. – Nit Mar 4 '14 at 0:28 • Without a > in the beginning to make a zero cell before the data this won't work in many interpreters/compilers. – Sylwester Mar 4 '14 at 9:25 • @Danek true, all the cells are initialized to zero and the first thing you do is to read the first digit into the very first cell. [.<] has no zero cell to stop at because of that and will fail. Error from bf -n rev1.bf is Error: Out of range! Youwanted to '<' below the first cell.. If you compile you get a segfault perhaps. – Sylwester Mar 4 '14 at 9:36 • +1 too even if BF is all about arrays so I'm not sure it fits the rule Do not use array – Michael M. Mar 4 '14 at 13:36 • @Nit echo is much shorter: ,[.,] – Cruncher Mar 4 '14 at 19:51 Haskell reverseNumber :: Integer -> Integer reverseNumber x = reverseNumberR x e 0 where e = 10 ^ (floor . logBase 10$ fromIntegral x)

reverseNumberR :: Integer -> Integer -> Integer -> Integer
reverseNumberR 0 _ _ = 0
reverseNumberR x e n = d * 10 ^ n + reverseNumberR (x - d * e) (e div 10) (n + 1)
where d = x div e


No arrays, strings, or modulus.

Also, I know we're not supposed to use lists or strings, but I love how short it is when you do that:

reverseNumber :: Integer -> Integer
reverseNumber = read . reverse . show

• A bunch of site regulars had maxed out their voting for the day, so have patience. :) – Jonathan Van Matre Mar 4 '14 at 2:58

C++

/*
A one-liner RECUrsive reveRSE function. Observe that the reverse of a 32-bit unsigned int
can overflow the type (eg recurse (4294967295) = 5927694924 > UINT_MAX), thus the
return type of the function should be a 64-bit int.

Usage: recurse(n)
*/

int64_t recurse(uint32_t n, int64_t reverse=0L)
{
return n ? recurse(n/10, n - (n/10)*10 + reverse * 10) : reverse;
}

• Would be cooler with ?: – mniip Mar 4 '14 at 21:05
• @mniip Good idea – Ali Alavi Mar 4 '14 at 21:10
• + 1 Brilliant. Wish there were more upvotes. – duci9y Mar 5 '14 at 6:46
• Kudos for catching the overflow case. – Jonathan Van Matre Mar 5 '14 at 15:56

I suppose someone has to be the partypooper.

Bash

$rev<<<[Input]  $ rev<<<321
123
$rev<<<1234567890 0987654321  Size limitations depend on your shell, but you'll be fine within reason. • well played sir. well played – user Mar 3 '14 at 21:20 • How is that not a string? – Not that Charles Mar 4 '14 at 5:26 • This might be a string. Are you sure bash takes input as integers when possible? – duci9y Mar 4 '14 at 6:31 • Everything is a string in Bash unless declared otherwise using for example declare -i. Compare foo=089 and declare -i foo=089 (invalid octal number). – l0b0 Mar 4 '14 at 10:11 • As per the comment by @l0b0 this answer is invalid. – duci9y Mar 4 '14 at 16:51 Javascript EDIT : Since there is a suggestion to not use % operator, I use a little trick now. I know this is not a code-golf, but there is no reason to make it longer. function r(n){v=0;while(n)v=n+10*(v-(n=~~(n/10)));return v}  r(13457) returns 75431 Moreover, it's a lot faster than string method (n.toString().split('').reverse().join('')) : ==> JSPerf report <== • What about using ~~ instead of Math.floor? – Victor Stafusa Mar 3 '14 at 18:01 • Yes that would be shorter, but less understandable. – Michael M. Mar 3 '14 at 18:07 • Isn't this the textbook integer-reversal method? I think I've written this algorithm for homework. – user2357112 Mar 3 '14 at 20:48 • As with the comment above, this is just the standard integer reversal algorithm. As far as I can see the creative part is just the usage of ~~ instead of Math.floor (the change suggested by @Victor) – Bertie Wheen Mar 4 '14 at 17:12 • +1 for performance testing. all the great creative minds do performance testing early and often. :D – Jonathan Van Matre Mar 5 '14 at 15:44 Python Not sure if this implementation qualifies for creative math Also % operator was not used per se, though one might argue that divmod does the same, but then then the Question needs to be rephrased :-) Implementation r=lambda n:divmod(n,10)[-1]*10**int(__import__("math").log10(n))+r(n /10)if n else 0  demo >>> r(12345) 54321 >>> r(1) 1  How does it work? This is a recursive divmod solution *This solution determines the least significant digit and then pushes it to the end of the number.* Yet Another Python Implementation def reverse(n): def mod(n, m): return n - n / m * m _len = int(log10(n)) return n/10**_len + mod(n, 10)*10**_len + reverse(mod(n, 10**_len)/10)*10 if n and _len else n  How does it work? This is a recursive solution which swaps the extreme digits from the number Reverse(n) = Swap_extreme(n) + Reverse(n % 10**int(log10(n)) / 10) ; n % 10**log10(n) / n is the number without the extreme digits ; int(log10(n)) is the number of digits - 1 ; n % 10**int(log10(n)) drops the most significant digit ; n / 10 drops the least significant digit Swap_extreme(n) = n/10**int(log10(n)) + n%10*10**int(log10(n)) ; n%10 is the least significant digit ; n/10**int(log10(n)) is the most significant digit  Example Run reverse(123456) = 123456/10^5 + 123456 % 10 * 10^5 + reverse(123456 % 10 ^ 5 / 10) = 1 + 6 * 10 ^ 5 + reverse(23456/10) = 1 + 600000 + reverse(2345) = 600001 + reverse(2345) reverse(2345) = 2345/10^3 + 2345 % 10 * 10^3 + reverse(2345 % 10 ^ 3 / 10) = 2 + 5 * 10^3 + reverse(345 / 10) = 2 + 5000 + reverse(34) = 5002 + reverse(34) reverse(34) = 34/10^1 + 34 % 10 * 10^1 + reverse(34 % 10 ^ 1 / 10) = 3 + 40 + reverse(0) = 43 + reverse(0) reverse(0) = 0 Thus reverse(123456) = 600001 + reverse(2345) = 600001 + 5002 + reverse(34) = 600001 + 5002 + 43 + reverse(0) = 600001 + 5002 + 43 + 0 = 654321  • It does. +5 brownie points. – duci9y Mar 3 '14 at 19:07 • @downvoter: Can you please respond what is wrong with this answer? – Abhijit Mar 7 '14 at 2:36 • you, sir, deserve my thumbs up ... – kmonsoor Mar 7 '14 at 4:54 Just to be contrary, an overuse of the modulo operator: unsigned int reverse(unsigned int n) {return n*110000%1099999999%109999990%10999900%1099000%100000;}  Note that this always reverses 5 digits, and 32 bit integers will overflow for input values more than 39045. C# Here's a way to do it without the Modulus (%) operator and just simple arithmetic. int x = 12356; int inv = 0; while (x > 0) { inv = inv * 10 + (x - (x / 10) * 10); x = x / 10; } return inv;  • You have modulus, you simply defined it yourself. – Benjamin Gruenbaum Mar 3 '14 at 22:23 • Yeah, I know. We're just not supposed to use the % operator. :) I see what you mean though, my text was a little misleading. – davidsbro Mar 3 '14 at 22:28 Bash > fold -w1 <<<12345 | tac | tr -d '\n' 54321  C #include <stdio.h> int main(void) { int r = 0, x; scanf("%d", &x); while (x > 0) { int y = x; x = 0; while (y >= 10) { y -= 10; ++x; } r = r*10 + y; } printf("%d\n", r); }  No strings, arrays, modulus or division. Instead, division by repeated subtraction. Mathematica Making an image out of number, reflecting it, partitioning it into the digits. Then there is two alternatives: 1. Compare each image of a reflected digit with prepared earlier images, replace it with the corresponding digit and construct the number out of this. 2. Reflect every digit separately, construct a new image, and pass it to the image recognition function. I did both reflectNumber[n_?IntegerQ] := ImageCrop[ ImageReflect[ Image@Graphics[ Style[Text@NumberForm[n, NumberSeparator -> {".", ""}], FontFamily -> "Monospace", FontSize -> 72]], Left -> Right], {Max[44 Floor[Log10[n] + 1], 44], 60}] reflectedDigits = reflectNumber /@ Range[0, 9]; reverse[0] := 0 reverse[n_?IntegerQ /; n > 0] := Module[{digits}, digits = ImagePartition[reflectNumber[1000 n], {44, 60}]; {FromDigits[ digits[[1]] /. (d_ :> # /; d == reflectedDigits[[# + 1]] & /@ Range[0, 9])], ToExpression@ TextRecognize[ ImageAssemble[ Map[ImageReflect[#, Left -> Right] &, digits, {2}]]]}] reverse[14257893] > {39875241, 39875241}  EDIT: Added padding of three zeroes, because TextRecognise works correctly only with integers > 999. • Kudos for the double reflection. Every good programmer should use reflection whenever possible. ;-) However, your first method doesn't work for your example on my system in MM9. – Jonathan Van Matre Mar 4 '14 at 5:35 • Now that's creative. – David Sanders Mar 4 '14 at 18:39 • I got best results alternating 9 and 4 in my pad (all 9s or all 1s tended to give occasional OCR glitches), but that's probably down to the difference in fonts. – Jonathan Van Matre Mar 5 '14 at 15:51 Lua function assemble(n,...) if ... then return 10*assemble(...)+n end return 0 end function disassemble(n,...) if n>0 then return disassemble(math.floor(n/10),n%10,...) end return ... end function reverse(n) return assemble(disassemble(n)) end  No arrays or strings used. The number is split into digits and reassembled using the arguments list. • Lua doesn't have arrays anyway. Has tables :P Otherwise varargs are arrays – Nowayz Mar 4 '14 at 13:24 • @Nowayz It has tables which can resemble arrays. Which is why I am not allowed to use them. And varargs aren't arrays :P – mniip Mar 4 '14 at 13:49 • But you're using %! :P – ntoskrnl Mar 5 '14 at 21:56 Python2 Assumes "unsigned integer" is 32-bit import math import sys a=input() p=int(math.log(a, 10)) b=a while b%10==0: sys.stdout.write('0') # if 1-char string is not allowed, use chr(48) instead b=b/10 if p==0: print a elif p==1: print a%10*10+a/10 elif p==2: print a%10*100+a%100/10*10+a/100 elif p==3: print a%10*1000+a%100/10*100+a%1000/100*10+a/1000 elif p==4: print a%10*10000+a%100/10*1000+a%1000/100*100+a%10000/1000*10+a/10000 elif p==5: print a%10*100000+a%100/10*10000+a%1000/100*1000+a%10000/1000*100+a%100000/10000*10+a/100000 elif p==6: print a%10*1000000+a%100/10*100000+a%1000/100*10000+a%10000/1000*1000+a%100000/10000*100+a%1000000/100000*10+a/1000000 elif p==7: print a%10*10000000+a%100/10*1000000+a%1000/100*100000+a%10000/1000*10000+a%100000/10000*1000+a%1000000/100000*100+a%10000000/1000000*10+a/10000000 elif p==8: print a%10*100000000+a%100/10*10000000+a%1000/100*1000000+a%10000/1000*100000+a%100000/10000*10000+a%1000000/100000*1000+a%10000000/1000000*100+a%100000000/10000000*10+a/100000000 elif p==9: print a%10*1000000000+a%100/10*100000000+a%1000/100*10000000+a%10000/1000*1000000+a%100000/10000*100000+a%1000000/100000*10000+a%10000000/1000000*1000+a%100000000/10000000*100+a%1000000000/100000000*10+a/1000000000  When given input 1230, it outputs 0321. • I just saw the edit of modulus operator... should I delete this post? – ace Mar 3 '14 at 18:38 • I don't think you should delete it, because it is a suggestion to not use it, not a rule: "Since this is a popularity contest, I suggest not using the modulus (%) operator in your code." – ProgramFOX Mar 3 '14 at 18:41 • Plus that huge if statement is practically ASCII art. – Jonathan Van Matre Mar 4 '14 at 2:54 Postscript /rev{0 exch{dup 10 mod 3 -1 roll 10 mul add exch 10 idiv dup 0 eq{pop exit}if}loop}def  No arrays, no strings, no variables. gs -q -dBATCH -c '/rev{0 exch{dup 10 mod 3 -1 roll 10 mul add exch 10 idiv dup 0 eq{pop exit}if}loop}def 897251 rev =' 152798  The same without mod (which is just a shortcut, so no big difference): /rev { 0 exch { dup 10 idiv dup 3 1 roll 10 mul sub 3 -1 roll 10 mul add exch dup 0 eq {pop exit} if } loop } def  C# This uses no strings or arrays, but does use the .NET Stack<T> type (EDIT: originally used modulus operator; now removed) public class IntegerReverser { public int Reverse(int input) { var digits = new System.Collections.Generic.Stack<int>(); int working = input; while (working / 10 > 0) { digits.Push(working - ((working / 10) * 10)); working = working / 10; } digits.Push(working); int result = 0; int mult = 1; while (digits.Count > 0) { result += digits.Pop() * mult; mult *= 10; } return result; } }  C In that the obvious solution is represented in a couple other languages, might as well post it in C. Golfed: r;main(n){scanf("%d",&n);for(;n;n/=10)r=r*10+n%10;printf("%d",r);}  Ungolfed: #include <stdio.h> int main() { int n, r = 0; scanf("%d", &n); for(;n;n/=10) { r = r * 10 + n % 10; } printf("%d", r); }  EDIT: Just saw the modulus edit. Golfed (no modulus): r;main(n){scanf("%d",&n);for(;n;n/=10)r=r*10+(n-10*(n/10));printf("%d",r);}  Ungolfed (no modulus): #include <stdio.h> int main() { int n, r, m = 0; scanf("%d", &n); for(;n;n/=10) { r=r*10+(n-10*(n/10)); } printf("%d", r); }  Java This is the this i've come up with, no strings, no arrays... not even variables (in Java I mind you): public static int reverse(int n) { return n/10>0?(int)(modulo(n,10)*Math.pow(10, count(n)))+reverse(n/10):(int)(modulo(n,10)*Math.pow(10,count(n))); } public static int count(int i) { return (i = i/10)>0?count(i)+1:0; } public static int modulo(int i,int j) { return (i-j)>=0?modulo(i-j, j):i; }  EDIT A more readable version /** Method to reverse an integer, without the use of String, Array (List), and %-operator */ public static int reverse(int n) { // Find first int to display int newInt = modulo(n,10); // Find it's position int intPos = (int) Math.pow(10, count(n)); // The actual value newInt = newInt*intPos; // Either add newInt to the recursive call (next integer), or return the found return (n/10>0) ? newInt+reverse(n/10) : newInt; } /** Use the stack, with a recursive call, to count the integer position */ public static int count(int i) { return (i = i/10)>0?count(i)+1:0; } /** A replacement for the modulo operator */ public static int modulo(int i,int j) { return (i-j)>=0?modulo(i-j, j):i; }  • Please make your code more readable, this is not code golf. Thank you. – duci9y Mar 4 '14 at 7:38 • This is my first attempt at this, i hope the updated version is better :-) – oiZo Mar 4 '14 at 8:08 • Yes it is. Thank you. Welcome to Code Golf. I'm new too. :) – duci9y Mar 4 '14 at 8:29 PowerShell A quick solution in PowerShell. No arrays or strings used, either implicitly or explicitly. function rev([int]$n) {
$x = 0 while ($n -gt 0) {
$x =$x * 10
$x +=$n % 10
$n = [int][math]::Floor($n / 10)
}
$x }  Testing: PS > rev(13457) 75431 PS > rev(rev(13457)) 13457  python (easily done in assembly) Reverses the bits of a byte. Points for not doing the exact same thing everyone else did? x = int(input("byte: "), 2) x = ((x * 8623620610) & 1136090292240) % 1023 print("{0:b}".format(x).zfill(8))  example byte: 10101010 01010101  • Would it work for the sample input to produce the sample output? – duci9y Mar 4 '14 at 6:38 C++ #include<iostream> #include<conio.h> #include<fstream> using namespace std; int main() { int i,size; float num; char ch; cout<<"enter the number \t: "; cin>>num; ofstream outf("tmp.tmp"); outf<<num; outf.close(); ifstream inf("tmp.tmp"); inf.seekg(0,ios::end); size=inf.tellg(); inf.seekg(-1,ios::cur); cout<<"Reverse of it\t\t: "; for(i=0;i<size;i++) { inf>>ch; if(ch!='0'||i!=0) cout<<ch; inf.seekg(-2,ios::cur); } inf.close(); remove("tmp.tmp"); getch(); return 0; }  OUTPUT Three sample runs Test with zeros It too reverses floating numbers!!! If you want to run this code then run it on your computer because it creates a temporary file during its run-time and I am not sure if online compilers would make a temporary file on your computer • Isn't writing to a file making it a string? – duci9y Mar 4 '14 at 6:36 • string is a combination of character with a null character at the end so, it is not a string but a combination of characters only – Mukul Kumar Mar 4 '14 at 6:51 • A string is a sequence of characters. Sorry, but this answer does not meet the constraints. – duci9y Mar 4 '14 at 6:59 • your definition to strings is wrong please go to this website (cs.stmarys.ca/~porter/csc/ref/c_cpp_strings.html) and read the last paragraph carefully.String is a combination of characters ENDED WITH A '\0' – Mukul Kumar Mar 4 '14 at 7:16 • I'm sorry, you are talking about C strings. I'm talking about strings in general. Your answer does not qualify. – duci9y Mar 4 '14 at 11:18 ECMAScript 6 reverse=x=>{ var k=-(l=(Math.log10(x)|0)), p=x=>Math.pow(10,x), s=x*p(l); for(;k;k++) s-=99*(x*p(k)|0)*p(l+k); return s }  Then: • reverse(12345) outputs 54321 • reverse(3240) outputs 423 • reverse(6342975) outputs 5792436 Fission $SX/
\S?L
K\O


This program reverses the input.

\$ echo -n '12345' | fsn tac.fsn
54321

• You just narrowly slip past the "Did the programming language exist before the question was asked?" test on this one. Fission looks like a cool entry to the esolang world - sort of "Befunge on acid with a shelf full of particle physics books." Nice! – Jonathan Van Matre Mar 5 '14 at 16:05

FORTH

I think this is the opposite of popular... but using Forth is always creative...

Let's create a new word

: REV
BEGIN
S->D 10 U/
SWAP 1 .R
DUP 0= UNTIL
CR ;


Here, it uses word U/ that returns remainder and quotient, remainder is sent to output as number within a field 1 character long, until dividend is zero. No string is used, at least until something is sent to video. I do not use a modulo operator, instead I use integer division with remainder and quotient. Let's try

12345 REV 54321
ok


• Where do I get that emulator? – cat Apr 23 '16 at 18:32
• World of Spectrum has plenty of emulators listed here worldofspectrum.org/emulators.html – Mattsteel May 16 '16 at 18:55

Python

import itertools

def rev(n):
l = next(m for m in itertools.count() if n/10**m == 0)
return sum((n-n/10**(i+1)*10**(i+1))/10**i*10**(l-i-1) for i in range(l))

• rev(1230) gives 321. I suppose it should really give 0321? – ace Mar 3 '14 at 18:37
• Is that wrong? If we are only dealing with numbers, not strings, then 0321 and 321 are equivalent right? – Jayanth Koushik Mar 3 '14 at 18:43
• It should be 321 to my understanding. The question disallowed using of strings. So it should be 321. – microbian Mar 3 '14 at 18:46
• I don't know... waiting for the OP's reply. I'm just pointing this out, not saying it's wrong. Sorry for the confusion. – ace Mar 3 '14 at 18:46
• I updated the question. – duci9y Mar 3 '14 at 18:47

C

#include <stdio.h>

int c(int n) {
return !n ? 0 : 1+c(n/10);
}

int p(int n) {
return !n ? 1 : 10*p(n-1);
}

int r(int n) {
return !n ? 0 : n%10*p(c(n/10))+r(n/10);
}

int main() {
printf("%d\n", r(13457));

return 0;
}


Batch

Missed the part about not using strings - oh well.

@echo off
setLocal enableDelayedExpansion enableExtensions
for /f %%a in ('copy /Z "%~dpf0" nul') do set "ASCII_13=%%a"
set num=%~1
set cnum=%num%
set len=0
:c
if defined num set num=%num:~1%&set /a len+=1&goto :c
set /a len-=1
for /L %%a in (%len%,-1,0) do set /p "=!ASCII_13!!cnum:~%%a,1!"<nul


Python 2

import math

def reverseNumber(num):
length = int(math.ceil(math.log10(num)))
reversed = 0

for i in range(0, length):
temp = num // math.pow(10, length - i - 1)
num -= temp * math.pow(10, length - i - 1)
reversed += int(temp * math.pow(10, i))

return reversed

print reverseNumber(12345)


C#

private static int ReverseNumber(int forwardNumber)
{

double forwardPower = 20;   //some number longer than Int32.MaxValue.Length
double reversePower = 0;
int reverseNumber=0;
bool realNumberStarted=false;

do
{
var tempInt= (int)(forwardNumber / Math.Pow(10, forwardPower));
tempInt = (int)((((decimal)tempInt / 10) - (tempInt / 10))*10);
if (tempInt>0 && !realNumberStarted)
{
realNumberStarted = true;
}
reverseNumber = reverseNumber+ tempInt * (int)Math.Pow(10, reversePower);
if (realNumberStarted)
{
reversePower++;
}

forwardPower--;
} while (forwardPower >=0);

return reverseNumber;
}


Outputs

Console.WriteLine( ReverseNumber(12345));
Console.WriteLine(ReverseNumber(67584930));


54321
3948576