किसी संख्या को उल्टा करने का सबसे छोटा तरीका


31

एक पूर्णांक मूल्यवान मान को स्वीकार करने के लिए एक फ़ंक्शन (या समतुल्य उपप्रोग्राम) लिखें और तर्क के आधार -10 अंकों के क्रम को उलट कर पाया गया (इसी प्रकार का टाइप) मान लौटाएं।

उदाहरण के लिए 76543 रिटर्न 34567 दिया गया


6
उस समय पर वापस जाएं जब संख्या एक स्ट्रिंग थी, फिर स्ट्रिंग को उल्टा करें
pmg

2
"सबसे छोटी एल्गोरिथ्म" का विचार कुछ हद तक प्रासंगिक है, खासकर यदि आप "किसी भी भाषा" की अनुमति देंगे। एक एल्गोरिथ्म के बारे में सोचें, और मैं आपको एक उपयुक्त "~" ऑपरेटर के साथ एक डीएसएल दे दूंगा ...

3
बस एक सूचना: 0 के साथ समाप्त होने वाली कोई भी संख्या उलट जाने पर अंकों की एक छोटी संख्या बन जाती है ...
powtac

44
मुझे एक एल्गोरिथ्म पता है जो बिल्कुल भी समय नहीं लेता है , लेकिन केवल
पैलिंड्रोमिक

खुद को फिर से लिखने का समय मिला। मुझे आशा है कि यह पहेली बनी रहेगी जिसे eltond का अर्थ मुद्रा बनाना है।
dmckee

जवाबों:


85

HTML 21 7 वर्ण (1 चेर अगर मैं चुटीला हूँ ...)

‮n

बदलने के nअपने नंबर से


1
यह सिर्फ सादा प्रतिभा है। मैं एक चार के लिए जाना था। या 2, क्योंकि यह UTF-16 में दो बाइट्स के लिए एनकोड करता है: P
tomsmeding

17
हाहा I ने उस टैग पर एक Google खोज की थी और उसे पुरस्कृत किया गया था Your search -‮ - किसी भी दस्तावेज़ से मेल नहीं खाता था।
JoeFish

U ब्राउज़र में इस लिंक को आज़मा सकता है:data:text/html,&%238238;egnahcxEkcatS olleH
F. Hauri

3
Google transate में भी मजेदार । @ जोएफ़िश: मैं पुन: पेश नहीं कर सकता, कृपया एक लिंक पोस्ट करें!
एफ HAURI

1
@JoeFish जब मैं टिप्पणी को देखता हूं, तो आपका उपयोगकर्ता नाम फ़्लिप किया जाता है और इसके बाद कुछ पाठ होता है। txet emos si ereH
स्टीफनोट

32

अजगर

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

संपादित करें:

@Gnibbler द्वारा सुझाए गए छोटे समाधान:

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

या, अगर ऊपर स्पष्ट नहीं है:

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

4
s[::-1]है की तुलना में बहुत तेजी से''.join(reversed(s))
रिज़ा

4
You can use backticks (for repr) instead of using str
gnibbler

@gnibbler Thanks for suggestion. I've updated my answer.
Vader

2
TBH, that ain't a function/proceduce/whatever you want to call it, and the specs require it.
Thomas Eding

Also, it doesn't even accept a value...
Exelian

28

Universal (language agnostic/independent)

If you want to use only numbers (avoid converting the number to string) and don't want to use some specific library (to be universal for any language):

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

This is python, but it could be done in any language, because it's just a math method.


If you replace mod with %, it's valid Python ;)
phihag

You're right, actually :) 10x

3
Not the shortest, but the most common and universal.
Kiril Kirov

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

1
BrainFuck doesn't, though it can be calculated. Any language that doesn't have it can use a - (n * int(a/n)) instead of a mod n. Also, if you look here, the modulus operation is implemented differently in every language. (See the table on the right.)
mbomb007

13

Perl 6

+$n.flip

or:

$n.flip

for dynamically typed code.

Numbers got string methods due to language design.


10

J - 6 characters + variable

".|.":y

Where y is your value.


2
As a function: |.&.": "reverse under do" which is pretty much a literal translation of the task.
FireFly



8

Befunge (3 characters)

Complete runnable program:

N.@

Where N is your number. Rules say "accept a single integer valued argument"; In Befunge you can only enter integers from 0 to 9.


3
Those are the only literals, but other numbers could certainly be represented. Otherwise, the winning answer would be Brainfuck with the empty program. ;-)
FireFly

8

Language-independent/mathematics

Inspired by Kiril Kirov's answer above. I got curious about the mathematical properties of reversing a number, so I decided to investigate a bit.

Turns out if you plot the difference n - rev(n) for natural numbers n in some base r, you get patterns like this ((n - rev(n)) / (r - 1), for r=10, wrapped at r columns, red denotes negative number):

table of differences

This sequence could be generated as such (pseudocode):

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)

If you store these values in a list/array, then n - arr[n] would get you the reversed form of n. Now, to "mathematically golf" this, we'd ideally want a closed-form expression that gives us the n:th value in the sequence, so that we could have a closed-form expression for solving the entire task. Unfortunately, I haven't been able to find such an expression... but it looks like it should be possible. :(

So yeah, not so much a code-golf as a mathematical curiosity, but if there is a closed-form expression of the above sequence it might actually be useful in proper PL golf submissions.


7

Haskell, 28 24 characters

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

2
How about f=read.reverse.show.(+0)?
FUZxxl

2
(+0): Legit man! Though technically you don't need the .(+0) at all, as f would be more polymorphic than what the problem requires (it is allowed to return a 'similarly typed' output). I would shave off those 5 characters.
Thomas Eding

7

Vim

17 chars

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

I would say that's 10 chars (keystrokes) if you type the command directly in vim. Btw, I learned something new in vim today, thanks :)
daniero

6

Scala - 33 Chars

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

1
+1 for scala, nice to see something else than python/ruby/perl
lhk

This will fail on negative Int. -123 should return -321
samach

6

Ruby (14)

x = 13456
x.to_s.reverse

3
"no" is undefined. I think you meant to put "x" there.
David Rivers

3
123456.to_s.reverse is even shorter.
Steffen Roller

@mmdemirbas - thanks for fixing the typo
bodacious

3
Needs to be .to_s.reverse.to_i to comply with spec.
histocrat

A number that starts with 0 doesnt seem to work. 0112.to_s.reverse.to_i => 47
Joel

5

It is possible to convert a number a string, then reverse the string and then convert that string back to number. This kind of feature is probably available in all language. If you are looking for a more mathematical method then this might help:

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

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

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.


हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.