40
\$\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\$

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

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

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

  • 1
    \$\begingroup\$ Is it a duplicate of codegolf.stackexchange.com/questions/2823/… ? \$\endgroup\$ – microbian Mar 3 '14 at 18:02
  • 3
    \$\begingroup\$ @microbian No, that one was code-golf. This one is popularity-contest. \$\endgroup\$ – Victor Stafusa Mar 3 '14 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\$ – Hosch250 Mar 3 '14 at 18:29
  • 2
    \$\begingroup\$ What if 1230 is the input? Are we allowed to output 321? (Otherwise, Strings are necessary). \$\endgroup\$ – Justin Mar 3 '14 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\$ – Mego Apr 22 '16 at 7:58

50 Answers 50

1
\$\begingroup\$

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

C++

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

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

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.

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

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

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

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

Golfscript

-1/

Pass an unsigned int as a command line arg

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

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

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

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

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

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

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

Javascript

function reverse(num) {
    for(var r = 0; num!=+[]; num = parseInt(num / 10, 10)) {
        r *= 10;
        r += num % 10;
    }
    return r;
}
\$\endgroup\$
  • \$\begingroup\$ I would appreciate if the one who voted -1 gave a reason for the same. :) \$\endgroup\$ – Clyde Lobo Mar 7 '14 at 8:52
0
\$\begingroup\$

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

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

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

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

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.

\$\endgroup\$

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