Most creative way to reverse a positive integer

40

8

Provided an input as an unsigned integer:

13457

Your function/subroutine should return:

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.

About Leading zeroes:

If the input is:

12340

Then the output:

4321

would be acceptable.

duci9y

Posted 2014-03-03T17:20:00.937

Reputation: 1 256

Question was closed 2016-04-22T16:57:02.963

2I'm voting to close this as off-topic because this lacks an objective validity criterion - "be creative" is subjective. – Mego – 2016-04-22T07:58:14.830

@Mego Man, the popularity-contest tag itself uses the word "creativity" as criteria. I don't know how 2 years later this question could be decided to be off topic. – duci9y – 2016-04-23T04:14:19.137

@duci9y We have since decided, as a community, that popcons must have objective validity criteria for what qualifies as a valid answer, and what specific qualities make an answer better than another. Relevant meta post: http://meta.codegolf.stackexchange.com/a/8093/45941

– Mego – 2016-04-23T04:16:11.843

Nope, uint all the way. – duci9y – 2014-03-03T17:35:42.227

Unicode can be embedded in other contexts than just HTML. That RTL override codepoint could appear anywhere – Gareth – 2014-03-03T17:35:46.363

@Gareth I updated the question. – duci9y – 2014-03-03T17:37:59.640

1

Is it a duplicate of http://codegolf.stackexchange.com/questions/2823/shortest-way-to-reverse-a-number ?

– microbian – 2014-03-03T18:02:28.257

3@microbian No, that one was code-golf. This one is popularity-contest. – Victor Stafusa – 2014-03-03T18:03:21.527

You probably need more exclusions if you want to see genuine creativity. e.g. Database tables, lists in languages where a list functions like an array. – Jonathan Van Matre – 2014-03-03T18:14:56.053

Can we use python generator objects? – Jayanth Koushik – 2014-03-03T18:20:55.147

By "cannot use strings", do you mean that there cannot be any strings, or that we cannot use strings to reverse the integer? – Justin – 2014-03-03T18:24:16.007

You can use generators @JayanthKoushik. No strings at all. – duci9y – 2014-03-03T18:26:05.400

@Gareth Your comment freaked me out a little. "Did I really post something an hour ago??" :-) – Gareth – 2014-03-03T18:26:07.133

@Gareth How is this possible? I am so confused... – Justin – 2014-03-03T18:28:14.220

@JonathanVanMatre What do you suggest to open it up more? Should I forbid the use of modulus, or something like that? – duci9y – 2014-03-03T18:28:38.377

2

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: http://meta.codegolf.stackexchange.com/questions/1117/proposed-questions-sandbox-mark-ix

– None – 2014-03-03T18:29:42.510

2What if 1230 is the input? Are we allowed to output 321? (Otherwise, Strings are necessary). – Justin – 2014-03-03T18:34:39.883

@Quincunx not really, see my answer – user12205 – 2014-03-03T18:41:28.383

The question is now ambiguous? What do you mean by 'suggest not using modulo'? Can we use it or can we not? Be clear. Also how can the rule be changed all of a sudden where most of the answers so far are using that modulo. By prohibiting modulo solutions will try to use arrays indirectly, like through lists and similar. Is that allowed? – microbian – 2014-03-03T18:52:43.350

The leading zeros example doesn't make much sense since it doesn't reverse. – Howard – 2014-03-03T18:52:44.207

@Howard Sorry :( updated. – duci9y – 2014-03-03T18:53:39.120

@microbian It is suggested not to use modulo, because that is the obvious solution, and this is a popularity contest. – duci9y – 2014-03-03T18:54:16.450

and everyone uses modulo! – TheDoctor – 2014-03-03T21:27:13.497

Answers

49

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:

honking big rasterized number

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:

honking big reversed number

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

Jonathan Van Matre

Posted 2014-03-03T17:20:00.937

Reputation: 2 307

2Beat me to it. You've got my vote!! [but I was going to use C#] – HL-SDK – 2014-03-04T02:49:46.113

1TextRegognize isn't working for small numbers. And you have typo in height = b[[3]];. Also check my answer too, please! :) – swish – 2014-03-04T03:50:29.980

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 – 2014-03-04T04:02:03.147

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 – 2014-03-04T05:24:18.300

Wow… that's elaborate! – duci9y – 2014-03-04T06:29:03.433

That's probably one of the more creative solutions I've seen for these type of questions. I wouldn't think to consider OCR :p – Thebluefish – 2014-03-05T15:04:57.717

I take admonitions to be creative to heart. :) – Jonathan Van Matre – 2014-03-05T15:42:16.407

39

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.

temp0.png

Then the whole number is again mirrored horizontally:

temp1.png

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 = font.read_tfm('cmtt10',size)
        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
        f = font.read_tfm(name,size)
      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__

Heiko Oberdiek

Posted 2014-03-03T17:20:00.937

Reputation: 3 841

6+1 for TeX. We need more TeX answers! – Jonathan Van Matre – 2014-03-05T15:54:41.090

25

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:

>,[>,]<[.<]

Danek

Posted 2014-03-03T17:20:00.937

Reputation: 361

@Mig Technically, some implementations for BF run with a pointer pointing to an allocated region of space. Instead of incrementing the index of the array, the pointer is incremented, etc. – frederick – 2015-07-11T13:56:54.543

@Nit And technically, it's a Tape, not an Array. – wizzwizz4 – 2016-04-22T16:51:14.057

4Shortest Bf program I've ever seen. Also, really neat. – Nit – 2014-03-04T00:28:05.133

2Without a > in the beginning to make a zero cell before the data this won't work in many interpreters/compilers. – Sylwester – 2014-03-04T09:25:59.047

That's a good point, @Sylwester, but in classical Brainfuck all the cells are set to 0 by default and you are starting with cell number 0, which is the first element of the memory array used, so it should not make a problem in a classical case, which is important.

– Danek – 2014-03-04T09:32:29.440

1@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 – 2014-03-04T09:36:07.660

@Sylwester, oh yeah, that's true! I'll add it to my answer, thanks a lot! – Danek – 2014-03-04T10:09:00.663

@Nit Well, you must be new here! – Blackhole – 2014-03-04T10:58:26.310

3+1 too even if BF is all about arrays so I'm not sure it fits the rule Do not use array – Michael M. – 2014-03-04T13:36:49.177

@Michael, Brainfuck's array is just the only possibility to store data and, consequently, to access the input stream, so I believe it is OK. – Danek – 2014-03-04T14:02:54.187

1@Nit echo is much shorter: ,[.,] – Cruncher – 2014-03-04T19:51:15.873

20

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

David Sanders

Posted 2014-03-03T17:20:00.937

Reputation: 300

2A bunch of site regulars had maxed out their voting for the day, so have patience. :) – Jonathan Van Matre – 2014-03-04T02:58:35.207

19

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;
}

Ali Alavi

Posted 2014-03-03T17:20:00.937

Reputation: 291

1Would be cooler with ?: – mniip – 2014-03-04T21:05:12.790

@mniip Good idea – Ali Alavi – 2014-03-04T21:10:00.990

>

  • 1 Brilliant. Wish there were more upvotes.
  • < – duci9y – 2014-03-05T06:46:53.110

    Kudos for catching the overflow case. – Jonathan Van Matre – 2014-03-05T15:56:19.417

    18

    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.

    Nit

    Posted 2014-03-03T17:20:00.937

    Reputation: 2 667

    rev operates on the data as a string: https://github.com/karelzak/util-linux/blob/master/text-utils/rev.c#L169 – David Sanders – 2015-07-16T16:38:34.397

    2well played sir. well played – user – 2014-03-03T21:20:28.147

    4How is that not a string? – Not that Charles – 2014-03-04T05:26:28.470

    1This might be a string. Are you sure bash takes input as integers when possible? – duci9y – 2014-03-04T06:31:00.880

    3Everything 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 – 2014-03-04T10:11:26.643

    3As per the comment by @l0b0 this answer is invalid. – duci9y – 2014-03-04T16:51:16.220

    1And even if bash thought it was a number, rev sure as hell doesn't. :) – Amadan – 2014-03-06T00:53:40.077

    15

    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('')) :

    enter image description here

    ==> JSPerf report <==

    Michael M.

    Posted 2014-03-03T17:20:00.937

    Reputation: 12 173

    2What about using ~~ instead of Math.floor? – Victor Stafusa – 2014-03-03T18:01:13.577

    Yes that would be shorter, but less understandable. – Michael M. – 2014-03-03T18:07:41.570

    2Isn't this the textbook integer-reversal method? I think I've written this algorithm for homework. – user2357112 supports Monica – 2014-03-03T20:48:33.190

    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 – 2014-03-04T17:12:28.270

    +1 for performance testing. all the great creative minds do performance testing early and often. :D – Jonathan Van Matre – 2014-03-05T15:44:55.480

    +1 ... although the comparison ain't fair since reverse() works for everything. – rafaelcastrocouto – 2014-03-06T17:07:33.423

    10

    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
    

    Abhijit

    Posted 2014-03-03T17:20:00.937

    Reputation: 2 841

    It does. +5 brownie points. – duci9y – 2014-03-03T19:07:51.903

    @downvoter: Can you please respond what is wrong with this answer? – Abhijit – 2014-03-07T02:36:57.343

    you, sir, deserve my thumbs up ... – kmonsoor – 2014-03-07T04:54:44.753

    9

    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.

    neonsignal

    Posted 2014-03-03T17:20:00.937

    Reputation: 99

    8

    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;
    

    davidsbro

    Posted 2014-03-03T17:20:00.937

    Reputation: 220

    You have modulus, you simply defined it yourself. – Benjamin Gruenbaum – 2014-03-03T22:23:52.093

    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 – 2014-03-03T22:28:05.023

    7

    Bash

    > fold -w1 <<<12345 | tac | tr -d '\n'
    54321
    

    Nik O'Lai

    Posted 2014-03-03T17:20:00.937

    Reputation: 585

    6

    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.

    David Conrad

    Posted 2014-03-03T17:20:00.937

    Reputation: 1 037

    6

    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.

    swish

    Posted 2014-03-03T17:20:00.937

    Reputation: 7 484

    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 – 2014-03-04T05:35:59.157

    Now that's creative. – David Sanders – 2014-03-04T18:39:59.757

    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 – 2014-03-05T15:51:46.483

    5

    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.

    mniip

    Posted 2014-03-03T17:20:00.937

    Reputation: 9 396

    Lua doesn't have arrays anyway. Has tables :P Otherwise varargs are arrays – Nowayz – 2014-03-04T13:24:59.480

    @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 – 2014-03-04T13:49:03.963

    But you're using %! :P – ntoskrnl – 2014-03-05T21:56:15.790

    5

    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.

    user12205

    Posted 2014-03-03T17:20:00.937

    Reputation: 8 752

    I just saw the edit of modulus operator... should I delete this post? – user12205 – 2014-03-03T18:38:28.483

    7I 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 – 2014-03-03T18:41:30.023

    Plus that huge if statement is practically ASCII art. – Jonathan Van Matre – 2014-03-04T02:54:42.203

    4

    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
    

    user2846289

    Posted 2014-03-03T17:20:00.937

    Reputation: 1 541

    4

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

    Comintern

    Posted 2014-03-03T17:20:00.937

    Reputation: 3 632

    4

    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;
        }
    }
    

    Edmund Schweppe

    Posted 2014-03-03T17:20:00.937

    Reputation: 209

    4

    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;
    }
    

    oiZo

    Posted 2014-03-03T17:20:00.937

    Reputation: 141

    Please make your code more readable, this is not code golf. Thank you. – duci9y – 2014-03-04T07:38:04.473

    1This is my first attempt at this, i hope the updated version is better :-) – oiZo – 2014-03-04T08:08:46.537

    Yes it is. Thank you. Welcome to Code Golf. I'm new too. :) – duci9y – 2014-03-04T08:29:29.687

    3

    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
    

    microbian

    Posted 2014-03-03T17:20:00.937

    Reputation: 2 297

    3

    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
    

    qwr

    Posted 2014-03-03T17:20:00.937

    Reputation: 8 929

    1Would it work for the sample input to produce the sample output? – duci9y – 2014-03-04T06:38:22.607

    3

    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
    enter image description here

    Test with zeros

    enter image description here

    It too reverses floating numbers!!!

    enter image description here

    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

    Mukul Kumar

    Posted 2014-03-03T17:20:00.937

    Reputation: 2 585

    Isn't writing to a file making it a string? – duci9y – 2014-03-04T06:36:45.447

    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 – 2014-03-04T06:51:04.017

    A string is a sequence of characters. Sorry, but this answer does not meet the constraints. – duci9y – 2014-03-04T06:59:18.650

    your definition to strings is wrong please go to this website (http://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 – 2014-03-04T07:16:14.970

    That is just an implementation detail. The first few lines of the link you posted says, "The term string generally means an ordered sequence of characters, with a first character, a second character, and so on…" – duci9y – 2014-03-04T07:18:22.060

    char a={'a','b','c','d', '\0' };('a' is a string) char a={'a','b','c','d'}; //'a' is a character combination but not a string. – Mukul Kumar – 2014-03-04T11:14:30.380

    1I'm sorry, you are talking about C strings. I'm talking about strings in general. Your answer does not qualify. – duci9y – 2014-03-04T11:18:37.330

    2

    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

    MT0

    Posted 2014-03-03T17:20:00.937

    Reputation: 3 373

    2

    Fission

    $SX/
    \S?L
    K\O
    

    This program reverses the input.

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

    C0deH4cker

    Posted 2014-03-03T17:20:00.937

    Reputation: 352

    1You 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 – 2014-03-05T16:05:24.147

    2

    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
    

    ZX Spectrum emulator

    Mattsteel

    Posted 2014-03-03T17:20:00.937

    Reputation: 381

    Where do I get that emulator? – cat – 2016-04-23T18:32:26.887

    World of Spectrum has plenty of emulators listed here http://www.worldofspectrum.org/emulators.html

    – Mattsteel – 2016-05-16T18:55:56.273

    2

    Turing Machine Code

    Using the syntax from here.

    0 * * l 0
    0 _ # r 2
    2 # # r 2
    2 0 # l A
    2 1 # l B
    2 2 # l C
    2 3 # l D
    2 4 # l E
    2 5 # l F
    2 6 # l G
    2 7 # l H
    2 8 # l I
    2 9 # l J
    2 _ _ l Z
    A * * l A
    A _ 0 l Q 
    B * * l B
    B _ 1 l Q 
    C * * l C
    C _ 2 l Q
    D * * l D
    D _ 3 l Q
    E * * l E
    E _ 4 l Q
    F * * l F
    F _ 5 l Q
    G * * l G
    G _ 6 l Q
    H * * l H
    H _ 7 l Q
    I * * l I
    I _ 8 l Q
    J * * l J
    J _ 9 l Q
    Q # # r 2
    Q * * r Q
    Z # _ l Z
    Z * * l ZZ
    ZZ _ * r ZZZ
    ZZ * * l ZZ
    ZZZ 0 _ r ZZZ
    ZZZ * * * halt
    

    Try it online!

    SuperJedi224

    Posted 2014-03-03T17:20:00.937

    Reputation: 11 342

    1

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

    Jayanth Koushik

    Posted 2014-03-03T17:20:00.937

    Reputation: 111

    rev(1230) gives 321. I suppose it should really give 0321? – user12205 – 2014-03-03T18:37:37.980

    Is that wrong? If we are only dealing with numbers, not strings, then 0321 and 321 are equivalent right? – Jayanth Koushik – 2014-03-03T18:43:20.440

    It should be 321 to my understanding. The question disallowed using of strings. So it should be 321. – microbian – 2014-03-03T18:46:13.647

    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. – user12205 – 2014-03-03T18:46:28.953

    I updated the question. – duci9y – 2014-03-03T18:47:19.693

    1

    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;
    }
    

    user17901

    Posted 2014-03-03T17:20:00.937

    Reputation: 19

    1

    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
    

    unclemeat

    Posted 2014-03-03T17:20:00.937

    Reputation: 2 302

    1

    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)
    

    vanchagreen

    Posted 2014-03-03T17:20:00.937

    Reputation: 11

    1

    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
    

    Brad

    Posted 2014-03-03T17:20:00.937

    Reputation: 141

    1

    C

    #include <stdio.h>
    #include <stdint.h>
    
    int main() {
        uint32_t n = 0;
        scanf("%u", &n);
    
        while (n) {
            uint64_t o = (uint64_t) n * 3435973837u;
            uint32_t r = o >> 35;
            putchar(n - r * 10 + '0');
            n = o >> 35;
        }
    
        return 0;
    }
    

    Convert division (with constant divisor) to multiplication. I used this page to generate the factor.

    The resulting code doesn't use / or % operators. Only >>, *, +, - are used.

    References

    n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

    Posted 2014-03-03T17:20:00.937

    Reputation: 5 683

    1

    C

    #include <stdio.h>
    #include <stdlib.h>
    
    unsigned  next_p( unsigned p )
    {
      unsigned  next =
        ( 8 & ((p << 1) & ((~p) << 2)) )     |
        ( 4 & (~p) )                         |
        ( 2 & ((p >> 2) | ((p >> 1) & p)) );
    
      return next;
    }
    
    unsigned  mAp( unsigned x, unsigned p )
    {
      unsigned  the_rest = 0;
    
      if (x > 1)
        the_rest = mAp( x >> 1, next_p(p) );
    
      if (x & 1)
        return (the_rest < 10 - p) ? the_rest + p : the_rest + p - 10;
      else if (x)
        return  the_rest;
      else
        return 0;
    }
    
    unsigned  fumA( unsigned x )
    {
      unsigned  v = mAp( x >> 1, 2 );
    
      if (x & 1)
        ++v;
    
      if (v < 10)
        return v;
    
      return fumA( v-10 );
    }
    
    
    unsigned  rflipper(unsigned x, unsigned *p)
    {
      unsigned  y = 0;
    
      if (x >= 10)
        y = rflipper( x / 10, p );
    
      y += fumA(x) * *p;
    
      (*p) *= 10;
    
      return y;
    }
    
    unsigned  rflip(unsigned x)
    {
      unsigned  p = 1;
    
      return rflipper(x, &p);
    }
    
    
    int main(int argc, char*argv[])
    {
      unsigned  i;
    
      if (argc < 2)
        {
          printf( "Useage:\n\t%s <positive integer>\n\n", argv[0] );
          return 0;
        }
    
      i = rflip(atoi(argv[1]));
    
      printf( "%d\n", i );
    
      return i;
    }
    

    Leland

    Posted 2014-03-03T17:20:00.937

    Reputation: 11

    1

    Extended BrainFuck

    ;;; variables
    :input
    :flag
    :zero
    
    ;;; macros
    ;; read byte with all EOF conventions 
    ;; + it also stops on linefeed
    ;; compatible BF interpreters translate CRLF => LF
    ;; so this would be portable
    ;; char value is one more than actual value
    {read_byte
       $flag +
       $input ,
       +[-[10-[11+$flag-]]]
       >[@flag-$zero]
    }
    
    ;; assumes current cell is empty
    ;; prints out a linefeed
    {linefeed
       10+.
    }
    
    ;; Assumes data starts to the left of current cell
    ;; prints until zero
    {print_bytes_left
     <[.<]
    }
    
    ;;; main program 
    while more $input + 
    ( - 
      >@input    ;; shift variables to the right
      &read_byte ;; read in byte
    )
    &print_bytes_left
    &linefeed
    

    Since someone beat me to a BF answer I rewrote it in EBF and made it portable and compatible. This doesn't wrap cells, it stops when encontering any one of the 3 EOF indicators or a linefeed. In compatible interpreters CRLF is translated to just a LF so this should work on any interpreter.

    Usage:

    % bf ebf.bf < rev.ebf > rev.bf
    % echo 2345 | bf -w rev.bf
    5432
    

    The resulting BrainFuck code (output of jitbf rev.bf --bf) is:

    -[+>>+<,+[-[----------[+++++++++>-]]]>[->]<<]<[.<]++++++++++.
    

    Same as with the previous answer and the other BF entry this just stores the input and print it in reverse order.

    I don't consider this an array since I made no way of random access (yes, I use arrays in (E)BF) so this is more a stack structure.

    Strings do not exist in BF but we do store them in similar manner as in this code.

    Sylwester

    Posted 2014-03-03T17:20:00.937

    Reputation: 3 678

    1Except for the first >, this was already posted. – hvd – 2014-03-04T08:52:57.710

    @hvd I didn't see that. Commented about missing > to the other poster and redid my answer to be different (more compatible). – Sylwester – 2014-03-04T09:32:17.567

    1

    C++

     int main()
        {
        int num =123456;
        int rev =0;
        while(num)
        {
        rev = (rev *10) + (num%10);
        num = num /10;
        }
        cout << "Reverse :" << rev;
        return 0;
        }
    

    kjk

    Posted 2014-03-03T17:20:00.937

    Reputation: 9

    1

    This program accepts anything from input and outputs it reversed. So it can reverse strings, integers, floating point numbers, leading zero numbers, and other stuff. Please note that I'm not using strings but chars, so it should be ok.

    PHP, HTML

    <?php
        while (false !== ($char = fgetc(STDIN))) {
        ?> <div style="float:right;"> <?= $char ?> </div> <?php
        }
    ?>
    

    I don't know if float:right would be considered a string or not, and just in case, here's a longer solution without that.

    PHP, HTML, CSS

    <style>
    div {
        float:right;
    }
    </style>
    
    <?php
        while (false !== ($char = fgetc(STDIN))) {
            ?> <div> <?= $char ?> </div> <?php
        }
    ?>
    

    Vereos

    Posted 2014-03-03T17:20:00.937

    Reputation: 4 079

    1

    PHP

    No (built in) modulo, no string, no array;

    function reverse ($n) {
        $r = 0;
        while ($n) {
            $r *= 10;
            $head = (int) ($n / 10);
            $r += $n - 10 * $head;
            $n = $head;
        }
    
        return $r;
    }
    

    Keven

    Posted 2014-03-03T17:20:00.937

    Reputation: 111

    1

    Golfscript

    -1/
    

    Pass an unsigned int as a command line arg

    Nowayz

    Posted 2014-03-03T17:20:00.937

    Reputation: 149

    1

    C#

    Using totally unnecessary recursion:

    int Reverse(int i)
    {
        return ReverseRecurse(i, 0);
    }
    
    int ReverseRecurse(int i, int r)
    {
        if (i==0) return r;
        else
        {
            int d= i/10;
            return ReverseRecurse(d, (10*r)+(i-(d*10)));
        }
    }
    

    Rik

    Posted 2014-03-03T17:20:00.937

    Reputation: 781

    1

    Python

    Probably not the best implementation, and I regret the need to import the math module, but here it is!

    import math
    
    def Reverse(n):
        revNum = 0
        digitsNum = math.floor(math.log10(n))
    
        for i in range(digitsNum, -1, -1):
            section = n // (10**(digitsNum-i))
            revNum += (section - 10*(section//10)) * 10**i
    
        return revNum
    

    buckley.w.david

    Posted 2014-03-03T17:20:00.937

    Reputation: 11

    1

    Java

    public class Reverser {
    
        public static long reverse(long x)
        {
            long n = (long) Math.floor(Math.log(x)/Math.log(10));
            long c = 0;
            for (long k=1; k<=n; k++)
            {
                c+= (long) (Math.floor( x * Math.pow(10, -1.0*k)) * Math.pow(10, n-k));
            }
    
            return (long) (x*Math.pow(10, n)) - (99 * c); 
    
        }
    
        public static void main (String args[])
        {
            long a= 1230504;
            long b= reverse(a);
            System.out.println(String.format("a=%d, b=%d", a,b));
        }
    }
    

    RobAu

    Posted 2014-03-03T17:20:00.937

    Reputation: 641

    1

    function recurse(accumulator) {
        var power = accumulator.power;
        accumulator.power *= 10;
        if (accumulator.input >= accumulator.power)
             recurse(accumulator);
        while (accumulator.input >= power) {
            accumulator.input -= power;
            accumulator.result += accumulator.value;
        }
        accumulator.value *= 10;
     }
    
     function reverse(x) {
        var accumulator = { power: 1, value: 1, input: x, result: 0 };
        recurse(accumulator);
        return accumulator.result;
     }
    

    Neil

    Posted 2014-03-03T17:20:00.937

    Reputation: 95 035

    1

    Java

    This code has the following limitations:

    1. it probably only works on the Eclipse console.
    2. it's limited to natural integers.
    3. it's artificially limited to a total of 100 figures (accross multiple calculations in sequence), this limit may be increased at the cost of performance, but the bottlenecks are probably the number of cores and the user's patience.
    4. it's not thread-safe. Use at your own risk.

    It essentially spawns a new Thread for each input byte and sleeps a bit less each time before writing it on the standard output.

    public static void main(String[] args) {
        System.out.println("Enter the number you want to reverse.");
        int i = -1;
        int count = 0;
        while (true) {
            try {
                i = System.in.read();
                final int readEntry = i;
                if(readEntry!=13&&readEntry!=10){
                    final int wait = count++;
                    new Thread(new Runnable(){
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(100-wait);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.print(readEntry-48);
                        }
                    }).start();
                }               
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    Thomas Philipakis

    Posted 2014-03-03T17:20:00.937

    Reputation: 111

    1

    C#

    Magic numbers and shifting bits... no division, no modulo, no chars, no strings, no arrays. Just integers, adding, bit shifts, and multiplication.

        static void Main(string[] args)
        {
            UInt32 uin = UInt32.Parse(Console.ReadLine());
            UInt32 usave = uin;
            UInt64 rl;
            UInt32 q;
            UInt32 uout = 0;
            int digits = 0;
            while (uin > 0){
                rl = (UInt64)3435973837*uin;
                uin = (UInt32)(rl >> 35);
                digits++;
            }
            uin = usave;
            while (uin > 0)
            {
                rl = (UInt64)3435973837 * uin;
                q = (UInt32)(rl >> 35);
                uout += (uin - q * 10)*(UInt32)Math.Pow(10,(digits-1));
                uin = q;
                digits--;
            }
            Console.WriteLine(uout);          
        }
    

    This answer actually has some utility because, although it is highly obfuscated, it provides a really fast way to simultaneously implement div 10 and modulo 10 in 64-bit code. See : How do I implement an efficient 32 bit DivMod in 64 bit code

    J...

    Posted 2014-03-03T17:20:00.937

    Reputation: 111

    0

    Javascript

    function reverse(num) {
        for(var r = 0; num!=+[]; num = parseInt(num / 10, 10)) {
            r *= 10;
            r += num % 10;
        }
        return r;
    }
    

    Clyde Lobo

    Posted 2014-03-03T17:20:00.937

    Reputation: 1 395

    I would appreciate if the one who voted -1 gave a reason for the same. :) – Clyde Lobo – 2014-03-07T08:52:04.500

    0

    C++11

    This code builds a function that prints an integer from STDIN in reverse, and then executes that function. Basically it is an example of really bad functional programming with loads of side effects.

    #include <cstdio>
    #include <functional>
    
    void r(std::function<void()> f) {
        char c = getchar();
        c > 47 && c < 58
        ?   r([=]() {
                putchar(c);
                f();
            })
        :   f();
    }
    
    int main() {
        r([]() {
            putchar(10);
        });
        return 0;
    }
    

    Fors

    Posted 2014-03-03T17:20:00.937

    Reputation: 3 020

    0

    Java

    int res = 0;
    int numb = 25455236;
    while(numb > 0){
      int temp = numb;
      int counter = 0;
      while (temp >= 0){
        temp = temp - 10;
        counter++;
      }
      res += 10-(counter*10-numb);
      res *= 10;
      numb = counter-1;
    }
    System.out.println(res/10);
    

    Howl Owl

    Posted 2014-03-03T17:20:00.937

    Reputation: 1

    0

    C

    No mod.

    #include <stdio.h>
    int main()
    {
        unsigned long n, m=0;
        scanf("%lx", &n);
        while( n ) m = m<<4 | n&0xF, n >>= 4;
        printf("%lx\n", m);
    }
    

    Florian F

    Posted 2014-03-03T17:20:00.937

    Reputation: 591

    0

    C

    Here is an actual procedure that takes an unsigned as input and returns the reversed value.

    unsigned long reverse(unsigned long n){
        unsigned long p=1, m=0, q=1;
        while( p<=n ) p *= 10;
        while( p /= 10 ){
            while( p<=n ) n -=p, m+= q;
            q *= 10;
        }
        return m;
    }
    

    Florian F

    Posted 2014-03-03T17:20:00.937

    Reputation: 591

    0

    Dart

    r(n, [a=0]) => n>0 ? r(n ~/ 10, a * 10 + n % 10) : a;
    

    Use as:

    main() { print(r(13457)); }  // prints 75431
    

    Only works for non-negative integers.

    lrn

    Posted 2014-03-03T17:20:00.937

    Reputation: 521