Il modo più breve per invertire un numero


31

Scrivi una funzione (o un sottoprogramma equivalente) per accettare un singolo argomento con valore intero e restituire un valore (tipizzato in modo simile) trovato invertendo l'ordine delle cifre di base 10 dell'argomento.

Ad esempio, dato 76543 restituisce 34567


6
Torna indietro nel tempo in cui il numero era una stringa, quindi inverti la stringa
pmg

2
L'idea di un "algoritmo più breve" è alquanto speciosa, soprattutto se consentirai "qualsiasi lingua". Pensa a un algoritmo e ti darò un DSL con un operatore "~" appropriato ...

3
Solo un avviso: qualsiasi numero che termina con 0 diventa un numero più breve di cifre quando viene invertito ...
powtac

44
Conosco un algoritmo che non richiede tempo , ma funziona solo su numeri palindromici;)
schnaader,

Ho trovato il tempo di scrivere da solo. Spero che questo rimanga il puzzle che Eltond intendeva porre.
dmckee,

Risposte:


85

HTML 21 7 caratteri (1 carattere se sono sfacciato ...)

‮n

sostituisci ncon il tuo numero


1
Questo è semplicemente un genio. Vorrei andare per un personaggio. O 2, poiché codifica in due byte in UTF-16: P
tomsmeding il

17
Hahaha Ho fatto una ricerca su Google su quel tag e sono stato premiato con Your search -‮ - non corrispondeva a nessun documento.
Joe Fish

Puoi provare questo link nel browser:data:text/html,&%238238;egnahcxEkcatS olleH
F. Hauri,

3
Divertente anche in Google Transate . @JoeFish: non riesco a riprodurre, per favore pubblica un link!
F. Hauri

1
@JoeFish Quando guardo il commento, il tuo nome utente viene capovolto e dopo c'è del testo. txet emos si ereH
Stefnotch,

32

Pitone

int(str(76543)[::-1])

MODIFICARE:

Soluzione più breve come suggerito da @gnibbler:

int(`76543`[::-1])

o, se sopra non è chiaro:

x=76543
int(`x`[::-1])

4
s[::-1]è molto più veloce di''.join(reversed(s))
riza l'

4
Puoi usare i backtick (per repr) invece di usare str
gnibbler

@gnibbler Grazie per il suggerimento. Ho aggiornato la mia risposta.
Vader,

2
TBH, che non è una funzione / procedura / come vuoi chiamarla, e le specifiche lo richiedono.
Thomas Eding,

Inoltre, non accetta nemmeno un valore ...
Exelian

28

Universale (linguaggio indipendente / indipendente )

Se vuoi usare solo numeri (evita di convertire il numero in stringa) e non vuoi usare qualche libreria specifica (per essere universale per qualsiasi lingua):

x = 76543 # or whatever is your number
y = 0
while x > 0:
    y *= 10
    y += ( x %10 )
    x /= 10 # int division 

Questo è Python, ma potrebbe essere fatto in qualsiasi lingua, perché è solo un metodo matematico.


Se lo sostituisci modcon %, è valido Python;)
phihag l'

Hai ragione, in realtà :) 10x

3
Non il più breve, ma il più comune e universale.
Kiril Kirov,

3
y=y*10+x%10....
via

1
BrainFuck no, anche se può essere calcolato. Qualsiasi lingua che non lo possiede può usare al a - (n * int(a/n))posto di a mod n. Inoltre, se si guarda qui , l'operazione del modulo è implementata in modo diverso in ogni lingua. (Vedi la tabella a destra.)
mbomb007

13

Perl 6

+$n.flip

o:

$n.flip

per codice digitato in modo dinamico.

I numeri hanno ottenuto metodi di stringa grazie al design del linguaggio.


10

J - 6 caratteri + variabile

".|.":y

Dove y è il tuo valore.


2
Come funzione: |.&.":"reverse under do", che è praticamente una traduzione letterale dell'attività.
FireFly


8

PHP, 9 caratteri

(int)strrev(123);

Per farla breve dov'è Nuna costante:

strrev(N)

8

Befunge (3 personaggi)

Programma eseguibile completo:

N.@

Dov'è il Ntuo numero. Le regole dicono "accetta un singolo argomento con valore intero "; In Befunge puoi inserire solo numeri interi da 0 a 9.


3
Questi sono gli unici letterali , ma altri numeri potrebbero certamente essere rappresentati. Altrimenti, la risposta vincente sarebbe Brainfuck con il programma vuoto. ;-)
FireFly

8

Indipendente dalla lingua / matematica

Ispirato dalla risposta di Kiril Kirov sopra. Mi sono incuriosito dalle proprietà matematiche dell'inversione di un numero, quindi ho deciso di indagare un po '.

Si scopre che se si traccia la differenza n - rev(n)per i numeri naturali nin una base r, si ottengono motivi come questo ( (n - rev(n)) / (r - 1), per r=10, avvolto in rcolonne, il rosso indica un numero negativo):

table of differences

Questa sequenza potrebbe essere generata come tale (pseudocodice):

for i=1 to r:
  output 0

for m=0, 1, …
  for k=1 to (r-1):
    for d=1 to r^m:
      for i=0 to (r-1):
        output (r-1) * (r+1)^m * (k - i)

Se memorizzi questi valori in un elenco / array, n - arr[n]otterrai la forma inversa di n. Ora, per "giocare matematicamente a golf", vorremmo idealmente un'espressione a forma chiusa che ci dia il valore n: esimo nella sequenza, in modo da poter avere un'espressione a forma chiusa per risolvere l'intero compito. Sfortunatamente, non sono stato in grado di trovare un'espressione simile ... ma sembra che dovrebbe essere possibile. :(

Quindi sì, non tanto un code-golf quanto una curiosità matematica, ma se esiste un'espressione in forma chiusa della sequenza sopra, potrebbe effettivamente essere utile nelle proposte di golf PL appropriate.


7

Haskell, 28 24 caratteri

f=read.reverse.show.(+0)

2
Che ne dici f=read.reverse.show.(+0)?
FUZxxl,

2
(+0): Legit man! Sebbene tecnicamente non ti serva .(+0)affatto, poiché fsarebbe più polimorfico di quanto il problema richieda (è consentito restituire un output "tipizzato in modo simile"). Vorrei radere quei 5 personaggi.
Thomas Eding,

7

Vim

17 caratteri

:se ri<CR>C<C-R>"

Direi che sono 10 caratteri (sequenze di tasti) se digiti il ​​comando direttamente in vim. A proposito, ho imparato qualcosa di nuovo in vim oggi, grazie :)
daniero il

6

Scala - 33 personaggi

def r(a:Int)=(a+"").reverse.toInt

1
+1 per scala, bello vedere qualcos'altro oltre a pitone / rubino / perl
lk

Questo fallirà su Int. Negativo. -123 dovrebbe restituire -321
samach

6

Rubino (14)

x = 13456
x.to_s.reverse

3
"no" non è definito. Penso che volevi mettere "x" lì.
David Rivers,

3
123456.to_s.reverse è ancora più breve.
Steffen Roller,

@mmdemirbas - grazie per aver risolto l'errore di battitura
corposo

3
Deve essere .to_s.reverse.to_iconforme alle specifiche.
istocratico,

Un numero che inizia con 0 non sembra funzionare. 0112.to_s.reverse.to_i => 47
Gioele,

5

È possibile convertire un numero in una stringa, quindi invertire la stringa e quindi riconvertire quella stringa in numero. Questo tipo di funzionalità è probabilmente disponibile in tutte le lingue. Se stai cercando un metodo più matematico, questo potrebbe aiutare:

int n = 76543;
int r = 0;

while (n > 0) {
    r *= 10;
    r += n % 10;
    n /= 10;
}

5
Mine is absolutely the same (:

Ya, only difference is your code looks like Python.

This method overflow's on languages with limited precision. try 1111111119
st0le

5

Python 3+

Function form: 28 characters

r=lambda i:int(str(i)[::-1])

(Sub)program form: 25 characters

print(input()[::-1])

I consider some of the other Python examples to be cheating, or at least cheap, due to using hardcoded input and/or not fully satisfying the requirements.


5

Golfscript, 5 chars

`-1%~

This takes an argument on the stack and leaves the result on the stack. I'm exploiting the "subprogram" option in the spec: if you insist on a function, that's four chars more leaving it on the stack:

{`-1%~}:r

I think you must've meant `-1%~ rather than `-1$~ (and I've taken the liberty of editing your answer to say so).
Ilmari Karonen

5

In shell scripting :

  echo "your number"|rev

Hope this was useful :)


good one! didn't know bash was capable to that also!
Pranit Bauva

1
I guess technically it does return a similarly-typed "number"... could be shortened further with rev<<<yournumber, e.g. rev<<<132 (for bash/zsh, not per POSIX though)
FireFly

1
Just rev is enough, the question doesn't say it has to be a function. You could compare rev to a built-in function, even though it's not one.
nyuszika7h

this is invalid: 'rev' is not a builtin, but an external program call.
Bastian Bittorf

67 Bytes pure POSIX shell: X=$1;while [ $X != 0 ];do Y=$((Y*10+X%10));X=$((X/10));done;echo $Y
Bastian Bittorf

3

Kinda late but

APL, 3

⍎⌽⍞

If you insists on a function

⍎∘⌽∘⍕

Well looks like I couldn't spot a duplicate above...(due to it being on the 2nd page)
TwiNight

I'm sad, that nobody gave brainfu*k or whitespace solution :( (one more vote and you're on the first page )
Kiril Kirov

@KirilKirov I've a brainfu*k solution : codegolf.stackexchange.com/a/32826/24829
rpax

3

Mathematica, 14 bytes

IntegerReverse

This is not competing, because this function was only added in last week's 10.3 release, but for completeness I thought I'd add the only ever (I think?) built-in for this task.


2

You could do the following in Java. Note that this converts to String and back and is not a mathematical solution.

public class test {
    public static int reverseInt(int i) {
        return Integer.valueOf((new StringBuffer(String.valueOf(i))).reverse().toString());
    }

    public static void main(String[] args) {
        int i = 1234;
        System.out.println("reverse("+i+") -> " + reverseInt(i));
    }
}

2
It is a mathematical solution. Mathematics is not numbers is not arithmetics. Mathematics also deals with strings of symbols. And in this special case, the conversion to and from string is just conversion to and from base-10.
R. Martinho Fernandes

What I meant by "not a mathematical solution" is that we're not doing any math ourselves. The methods are doing all of the parsing and mathematics for us. As opposed to e.g. Kiril Kirov's answer.
Victor

Will Overflow...
st0le

2

Lua

Numbers and strings are interchangeable, so this is trivial

string.reverse(12345)

2

This one ACTUALLY takes an input, unlike some of the rest:

print`input()`[::-1]

Python btw.


2

Actionscript

43 characters. num as the parameter to the function:

num.toString().split('').reverse().join('')

2

Groovy

r={"$it".reverse() as BigDecimal}

assert r(1234) == 4321
assert r(345678987654567898765) == 567898765456789876543
assert r(345346457.24654654) == 45645642.754643543

2

Perl, 11 chars

The p flag is needed for this to work, included in the count.

Usage:

$ echo 76543 | perl -pE '$_=reverse'

I count 10 chars
F. Hauri

The p flag is included in the count
Zaid

2

Clojure (42 chars)

#(->> % str reverse(apply str)read-string)

Example usage:

(#(->> % str reverse(apply str)read-string) 98321)

returns 12389


2

Common Lisp - 60 chars

(first(list(parse-integer(reverse(write-to-string '4279)))))

will get you 9724.


Why (first(list? parse-integer already returns the number.
Florian Margaine

2

K, 3 bytes:

.|$

Evaluate (.) the reverse (|) of casting to a string ($).

Usage example:

  .|$76543
34567

2

rs, 20 bytes

#
+#(.*)(.)/\2#\1
#/

Technically, this doesn't count (rs was created earlier this year), but I didn't see any other regex-based answers, and I thought this was neat.

Live demo.

Explanation:

#

Insert a pound character at the beginning of the string. This is used as a marker.

+#(.*)(.)/\2#\1

Continuously prepend the last character of the main string to the area before the marker until there are no characters left.

#/

Remove the marker.


2

mIRC 4.45 (35 Bytes)

$regsubex(12,/(.)/g,$mid(\A,-\n,1))
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.