41
\$\begingroup\$

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.

\$\endgroup\$
24
  • 1
    \$\begingroup\$ Is it a duplicate of codegolf.stackexchange.com/questions/2823/… ? \$\endgroup\$
    – microbian
    Commented Mar 3, 2014 at 18:02
  • 3
    \$\begingroup\$ @microbian No, that one was code-golf. This one is popularity-contest. \$\endgroup\$ Commented Mar 3, 2014 at 18:03
  • 2
    \$\begingroup\$ 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/… \$\endgroup\$
    – user10766
    Commented Mar 3, 2014 at 18:29
  • 2
    \$\begingroup\$ What if 1230 is the input? Are we allowed to output 321? (Otherwise, Strings are necessary). \$\endgroup\$
    – Justin
    Commented Mar 3, 2014 at 18:34
  • 2
    \$\begingroup\$ I'm voting to close this as off-topic because this lacks an objective validity criterion - "be creative" is subjective. \$\endgroup\$
    – user45941
    Commented Apr 22, 2016 at 7:58

50 Answers 50

49
\$\begingroup\$

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
\$\endgroup\$
7
  • 2
    \$\begingroup\$ Beat me to it. You've got my vote!! [but I was going to use C#] \$\endgroup\$
    – HL-SDK
    Commented Mar 4, 2014 at 2:49
  • 1
    \$\begingroup\$ TextRegognize isn't working for small numbers. And you have typo in height = b[[3]];. Also check my answer too, please! :) \$\endgroup\$
    – swish
    Commented Mar 4, 2014 at 3:50
  • \$\begingroup\$ Another problem with TextRecognize, is that it returns a String, which isn't allowed and also you need to convert it back to number. \$\endgroup\$
    – swish
    Commented Mar 4, 2014 at 4:02
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 4, 2014 at 5:24
  • \$\begingroup\$ Wow… that's elaborate! \$\endgroup\$
    – duci9y
    Commented Mar 4, 2014 at 6:29
41
\$\begingroup\$

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__
\$\endgroup\$
1
  • 8
    \$\begingroup\$ +1 for TeX. We need more TeX answers! \$\endgroup\$ Commented Mar 5, 2014 at 15:54
25
\$\begingroup\$

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:

>,[>,]<[.<]
\$\endgroup\$
11
  • 4
    \$\begingroup\$ Shortest Bf program I've ever seen. Also, really neat. \$\endgroup\$
    – Etheryte
    Commented Mar 4, 2014 at 0:28
  • 2
    \$\begingroup\$ Without a > in the beginning to make a zero cell before the data this won't work in many interpreters/compilers. \$\endgroup\$
    – Sylwester
    Commented Mar 4, 2014 at 9:25
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Sylwester
    Commented Mar 4, 2014 at 9:36
  • 3
    \$\begingroup\$ +1 too even if BF is all about arrays so I'm not sure it fits the rule Do not use array \$\endgroup\$
    – Michael M.
    Commented Mar 4, 2014 at 13:36
  • 1
    \$\begingroup\$ @Nit echo is much shorter: ,[.,] \$\endgroup\$
    – Cruncher
    Commented Mar 4, 2014 at 19:51
20
\$\begingroup\$

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
\$\endgroup\$
1
  • 2
    \$\begingroup\$ A bunch of site regulars had maxed out their voting for the day, so have patience. :) \$\endgroup\$ Commented Mar 4, 2014 at 2:58
18
\$\begingroup\$

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.

\$\endgroup\$
7
  • 2
    \$\begingroup\$ well played sir. well played \$\endgroup\$
    – user
    Commented Mar 3, 2014 at 21:20
  • 4
    \$\begingroup\$ How is that not a string? \$\endgroup\$ Commented Mar 4, 2014 at 5:26
  • 1
    \$\begingroup\$ This might be a string. Are you sure bash takes input as integers when possible? \$\endgroup\$
    – duci9y
    Commented Mar 4, 2014 at 6:31
  • 3
    \$\begingroup\$ 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). \$\endgroup\$
    – l0b0
    Commented Mar 4, 2014 at 10:11
  • 3
    \$\begingroup\$ As per the comment by @l0b0 this answer is invalid. \$\endgroup\$
    – duci9y
    Commented Mar 4, 2014 at 16:51
18
\$\begingroup\$

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;
}
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Would be cooler with ?: \$\endgroup\$
    – mniip
    Commented Mar 4, 2014 at 21:05
  • \$\begingroup\$ @mniip Good idea \$\endgroup\$
    – Ali Alavi
    Commented Mar 4, 2014 at 21:10
  • \$\begingroup\$ + 1 Brilliant. Wish there were more upvotes. \$\endgroup\$
    – duci9y
    Commented Mar 5, 2014 at 6:46
  • \$\begingroup\$ Kudos for catching the overflow case. \$\endgroup\$ Commented Mar 5, 2014 at 15:56
14
\$\begingroup\$

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

\$\endgroup\$
6
  • 2
    \$\begingroup\$ What about using ~~ instead of Math.floor? \$\endgroup\$ Commented Mar 3, 2014 at 18:01
  • \$\begingroup\$ Yes that would be shorter, but less understandable. \$\endgroup\$
    – Michael M.
    Commented Mar 3, 2014 at 18:07
  • 2
    \$\begingroup\$ Isn't this the textbook integer-reversal method? I think I've written this algorithm for homework. \$\endgroup\$ Commented Mar 3, 2014 at 20:48
  • \$\begingroup\$ 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) \$\endgroup\$ Commented Mar 4, 2014 at 17:12
  • \$\begingroup\$ +1 for performance testing. all the great creative minds do performance testing early and often. :D \$\endgroup\$ Commented Mar 5, 2014 at 15:44
10
\$\begingroup\$

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
\$\endgroup\$
3
  • \$\begingroup\$ It does. +5 brownie points. \$\endgroup\$
    – duci9y
    Commented Mar 3, 2014 at 19:07
  • \$\begingroup\$ @downvoter: Can you please respond what is wrong with this answer? \$\endgroup\$
    – Abhijit
    Commented Mar 7, 2014 at 2:36
  • \$\begingroup\$ you, sir, deserve my thumbs up ... \$\endgroup\$
    – kmonsoor
    Commented Mar 7, 2014 at 4:54
9
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

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;
\$\endgroup\$
2
  • \$\begingroup\$ You have modulus, you simply defined it yourself. \$\endgroup\$ Commented Mar 3, 2014 at 22:23
  • \$\begingroup\$ Yeah, I know. We're just not supposed to use the % operator. :) I see what you mean though, my text was a little misleading. \$\endgroup\$
    – davidsbro
    Commented Mar 3, 2014 at 22:28
7
\$\begingroup\$

Bash

> fold -w1 <<<12345 | tac | tr -d '\n'
54321
\$\endgroup\$
6
\$\begingroup\$

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.

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

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.

\$\endgroup\$
3
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 4, 2014 at 5:35
  • \$\begingroup\$ Now that's creative. \$\endgroup\$ Commented Mar 4, 2014 at 18:39
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 5, 2014 at 15:51
5
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ Lua doesn't have arrays anyway. Has tables :P Otherwise varargs are arrays \$\endgroup\$
    – Nowayz
    Commented Mar 4, 2014 at 13:24
  • \$\begingroup\$ @Nowayz It has tables which can resemble arrays. Which is why I am not allowed to use them. And varargs aren't arrays :P \$\endgroup\$
    – mniip
    Commented Mar 4, 2014 at 13:49
  • \$\begingroup\$ But you're using %! :P \$\endgroup\$
    – ntoskrnl
    Commented Mar 5, 2014 at 21:56
5
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ I just saw the edit of modulus operator... should I delete this post? \$\endgroup\$
    – user12205
    Commented Mar 3, 2014 at 18:38
  • 7
    \$\begingroup\$ 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." \$\endgroup\$
    – ProgramFOX
    Commented Mar 3, 2014 at 18:41
  • \$\begingroup\$ Plus that huge if statement is practically ASCII art. \$\endgroup\$ Commented Mar 4, 2014 at 2:54
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

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;
    }
}
\$\endgroup\$
4
\$\begingroup\$

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);
}
\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Would it work for the sample input to produce the sample output? \$\endgroup\$
    – duci9y
    Commented Mar 4, 2014 at 6:38
4
\$\begingroup\$

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;
}
\$\endgroup\$
3
  • \$\begingroup\$ Please make your code more readable, this is not code golf. Thank you. \$\endgroup\$
    – duci9y
    Commented Mar 4, 2014 at 7:38
  • 1
    \$\begingroup\$ This is my first attempt at this, i hope the updated version is better :-) \$\endgroup\$
    – hw4m
    Commented Mar 4, 2014 at 8:08
  • \$\begingroup\$ Yes it is. Thank you. Welcome to Code Golf. I'm new too. :) \$\endgroup\$
    – duci9y
    Commented Mar 4, 2014 at 8:29
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
7
  • \$\begingroup\$ Isn't writing to a file making it a string? \$\endgroup\$
    – duci9y
    Commented Mar 4, 2014 at 6:36
  • \$\begingroup\$ 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 \$\endgroup\$ Commented Mar 4, 2014 at 6:51
  • \$\begingroup\$ A string is a sequence of characters. Sorry, but this answer does not meet the constraints. \$\endgroup\$
    – duci9y
    Commented Mar 4, 2014 at 6:59
  • \$\begingroup\$ 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' \$\endgroup\$ Commented Mar 4, 2014 at 7:16
  • 1
    \$\begingroup\$ I'm sorry, you are talking about C strings. I'm talking about strings in general. Your answer does not qualify. \$\endgroup\$
    – duci9y
    Commented Mar 4, 2014 at 11:18
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

Fission

$SX/
\S?L
K\O

This program reverses the input.

$ echo -n '12345' | fsn tac.fsn
54321
\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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! \$\endgroup\$ Commented Mar 5, 2014 at 16:05
2
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ Where do I get that emulator? \$\endgroup\$
    – cat
    Commented Apr 23, 2016 at 18:32
  • \$\begingroup\$ World of Spectrum has plenty of emulators listed here worldofspectrum.org/emulators.html \$\endgroup\$ Commented May 16, 2016 at 18:55
2
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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))
\$\endgroup\$
5
  • \$\begingroup\$ rev(1230) gives 321. I suppose it should really give 0321? \$\endgroup\$
    – user12205
    Commented Mar 3, 2014 at 18:37
  • \$\begingroup\$ Is that wrong? If we are only dealing with numbers, not strings, then 0321 and 321 are equivalent right? \$\endgroup\$ Commented Mar 3, 2014 at 18:43
  • \$\begingroup\$ It should be 321 to my understanding. The question disallowed using of strings. So it should be 321. \$\endgroup\$
    – microbian
    Commented Mar 3, 2014 at 18:46
  • \$\begingroup\$ 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. \$\endgroup\$
    – user12205
    Commented Mar 3, 2014 at 18:46
  • \$\begingroup\$ I updated the question. \$\endgroup\$
    – duci9y
    Commented Mar 3, 2014 at 18:47
1
\$\begingroup\$

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;
}
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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)
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.