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

• 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/… – user10766 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

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


# 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 );
return 0;
}

i = rflip(atoi(argv));

printf( "%d\n", i );

return i;
}


C++

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


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


# 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
$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. # 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;
}


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

# Golfscript

-1/


Pass an unsigned int as a command line arg

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


# 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


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

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


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

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 {
final int wait = count++;
@Override
public void run() {
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}


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

Javascript

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

• I would appreciate if the one who voted -1 gave a reason for the same. :) – Clyde Lobo Mar 7 '14 at 8:52

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


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


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


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


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