反转正整数的最有创意的方法


40

提供的输入为无符号整数:

13457

您的函数/子例程应返回:

75431

由于这是一次人气竞赛,因此要有创造力。创新的解决方案使用不寻常或巧妙的技术来完成给定的任务。

限制条件:

  • 您不能使用数组。
  • 您不能使用字符串。
  • 无RTL替代(&#8238

布朗尼点使用创造性算术。

由于这是一场人气竞赛,因此建议不要%在代码中使用modulo()运算符。

关于前导零:

如果输入是:

12340

然后输出:

4321

是可以接受的。



3
@microbian不,那个是代码高尔夫。这是一场人气比赛。
维克多·斯塔夫萨

2
如果您现在开始更改规则,将会打勾人。这似乎是想没什么问题,只是先运行通过沙箱您的下一个挑战:meta.codegolf.stackexchange.com/questions/1117/...
Hosch250

2
如果1230输入怎么办?我们可以输出321吗?(否则,必须使用字符串)。
贾斯汀

2
我投票关闭此主题,因为它缺乏客观的有效性标准-“具有创造力”是主观的。
Mego

Answers:


49

Mathematica,无模!

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

让我们分解一下。

首先,我们使用一些“创意算术”来找出数字中的位数: length = Ceiling[Log[10, n]];

接下来,我们将数字栅格化为漂亮的大图像:

鸣喇叭大栅格化数字

现在,我们查询该图像的边界框,并填充宽度和高度(实际上使用基线偏移量而不是图像高度,因为MM在图像的基线下方添加了一些空白)。

接下来,NestList以递归的方式减去图像的宽度除以字符串的长度,以使ImageTake可以从图像末尾一一抽取字符,然后由ImageAssemble将这些字符重新组合为该图像:

鸣喇叭大倒数

然后,将其传递给用于光学字符识别的TextRecognize函数,该函数在此图像大小和光栅化质量下可以无瑕地识别最终输出,并为我们提供整数:

72641

对数和OCR-就像巧克力和花生酱!

新的和改进的

此版本填充数字以处理带有小数字的TextRecognize顽固行为,然后在末尾减去填充。这甚至适用于一位数字!

不过,为什么您要对一个数字执行反向例程对我来说还是个谜。但是为了完整起见,我什至使它适用于零和一的输入,这通常会中断,因为底日志不会为它们返回1。

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

2
击败我。你有我的投票!![但是我打算使用C#]
HL-SDK

1
TextRegognize对少量数字不起作用。而且您有错别字height = b[[3]];。也请检查我的答案!:)
2014年

的另一个问题TextRecognize是,它返回一个字符串,这是不允许的,并且您还需要将其转换回数字。
2014年

感谢您发现错字...我在提交变量名之前让变量名更易于阅读,但错过了一个。也丢了丢失的ToExpression。我发布了一个修订,该修订一直处理小数位数问题,一直到个位数。
乔纳森·范·马特雷

哇...很精致!
duci9y 2014年

39

Perl / LuaTeX / Tesseract

以下Perl脚本将数字作为命令行参数读取,例如:

    1234567890

以下Perl脚本通过LuaTeX打印数字。动态创建一个虚拟字体,该字体水平反映数字。

temp0.png

然后将整个数字再次水平镜像:

temp1.png

最终图像通过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__

6
+1表示TeX。我们需要更多TeX答案!
Jonathan Van Matre 2014年

25

脑干

基本上,它只是一个输入反转程序。

,[>,]<[.<]

UPD:正如Sylwester在评论中所指出的那样,在经典的Brainfuck解释器/编译器中(不可能从存储阵列的零点开始向左移动),该程序在开始时没有'>'时将无法工作,因此更加稳定版本是:

>,[>,]<[.<]

4
我见过的最短的Bf程序。另外,真的很整洁。
Nit 2014年

2
如果没有>在数据开始之前先使单元格为零,则在许多解释器/编译器中将无法正常工作。
Sylwester 2014年

1
@Danek是的,所有单元格都初始化为零,您要做的第一件事是将第一个数字读入第一个单元格。[.<]因此,没有零个单元格可以停止,并且将失败。从错误bf -n rev1.bfIS Error: Out of range! Youwanted to '<' below the first cell.。如果您进行编译,则segfault可能会得到结果。
Sylwester 2014年

3
即使BF只是关于数组,也是如此+1,所以我不确定它是否符合规则。不要使用数组
Michael M.

1
@Nit回声要短得多:,[.,]
Cruncher

20

哈斯克尔

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

没有数组,字符串或模数。

另外,我知道我们不应该使用列表或字符串,但是我喜欢这样做的时间有多短:

reverseNumber :: Integer -> Integer
reverseNumber = read . reverse . show

2
一群网站常客在当天的投票中发挥了最大作用,因此也要有耐心。:)
乔纳森·范·马特雷

19

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

1
使用?:
mniip

@mniip好主意
Ali Alavi

+ 1辉煌 希望有更多的支持。
duci9y 2014年

捕捉溢出情况的荣誉。
Jonathan Van Matre 2014年

18

我想有人必须当派对。

重击

$ rev<<<[Input]

 

$ rev<<<321
123
$ rev<<<1234567890
0987654321

大小限制取决于您的外壳,但您在合理范围内会没事的。


2
先生打得好。玩得很好
用户

4
那怎么不是字符串?
不是查尔斯(Charles)

1
可能是一个字符串。您确定bash尽可能将输入作为整数吗?
duci9y

3
除非使用example声明,否则一切都是Bash中的字符串declare -i。比较foo=089declare -i foo=089(无效的八进制数)。
l0b0

3
根据@ l0b0的评论,此答案无效。
duci9y 2014年

15

Java脚本

编辑:由于有建议不要使用%运算符,所以我现在使用一些技巧。

我知道这不是一个代码问题,但是没有理由延长它的时间。

function r(n){v=0;while(n)v=n+10*(v-(n=~~(n/10)));return v}

r(13457) 退货 75431

而且,它比字符串方法(n.toString().split('').reverse().join(''))快得多:

在此处输入图片说明

==> JSPerf报告<==


2
那用~~代替Math.floor呢?
维克多·斯塔夫萨

是的,那会更短一些,但难以理解。
Michael M.

2
这不是教科书的整数反转方法吗?我想我已经为作业写了这种算法。
user2357112 2014年

就像上面的评论一样,这只是标准的整数反转算法。据我所见,创意部分只是~~而不是Math.floor(@Victor建议的更改)的使用
Bertie Wheen

+1用于性能测试。所有伟大的创意人士都尽早且经常进行性能测试。:D
乔纳森·范马特雷

10

蟒蛇

不确定此实现是否符合创造性数学的条件

同样,%操作符本身并没有使用,尽管有人可能会说divmod做了同样的事情,但是然后这个问题需要改写:-)

实作

r=lambda n:divmod(n,10)[-1]*10**int(__import__("math").log10(n))+r(n /10)if n else 0

演示

>>> r(12345)
54321
>>> r(1)
1

它是如何工作的?

这是递归的divmod解决方案 *此解决方案确定最低有效数字,然后将其推到数字的末尾。*

另一个Python实现

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

它是如何工作的?

这是一种递归解决方案,可将数字中的极端数字互换

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

示例运行

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

是的 + 5果仁巧克力点
duci9y 2014年

@downvoter:能否请您回答这个答案有什么问题?
阿比吉特(Abhijit)2014年

先生,您值得我竖起大拇指……
kmonsoor

9

恰恰相反,模运算符的过度使用:

unsigned int reverse(unsigned int n)
    {return n*110000%1099999999%109999990%10999900%1099000%100000;}

请注意,这始终会反转5位数字,并且输入值超过39045时32位整数将溢出。


8

C#

这是一种无需使用Modulus(%)运算符而只需简单算术的方法。

int x = 12356;
int inv = 0;
while (x > 0)
{
    inv = inv * 10 + (x - (x / 10) * 10);
    x = x / 10;
}
return inv;

您拥有模数,只需自己定义即可。
Benjamin Gruenbaum 2014年

是的,我知道。我们只是不应该使用%运算符。:)我明白了您的意思,但是我的文字有些误导。
davidsbro 2014年


6

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

没有字符串,数组,模数或除法。取而代之的是通过反复减法相除。


6

Mathematica

用数字制作图像,将其反映出来,然后将其划分为数字。然后有两种选择:

  1. 将反射的手指的每个图像与准备好的较早的图像进行比较,将其替换为相应的手指,然后从中构造数字。

  2. 分别反映每个数字,构造一个新图像,并将其传递给图像识别功能。

我都做过

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}

编辑:添加了三个零的填充,因为TextRecognise只有在整数> 999的情况下才能正常工作。


双重反射的荣誉。每个好的程序员都应尽可能使用反射。;-)但是,您的第一种方法不适用于MM9中我的系统上的示例。
Jonathan Van Matre 2014年

现在这很有创意。
大卫·桑德斯

我在垫板上交替使用9和4可获得最佳结果(所有9或全部1都会偶尔出现OCR故障),但这可能归因于字体的差异。
Jonathan Van Matre 2014年

5

a

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

不使用数组或字符串。该数字被分成数字,并使用参数列表重新组合。


Lua仍然没有数组。有表:P否则varargs是数组
Nowayz 2014年

@Nowayz它的表可以类似于数组。这就是为什么不允许我使用它们的原因。而且varargs不是数组:P
mniip 2014年

但是您正在使用%!:P
ntoskrnl 2014年

5

Python2

假设“无符号整数”是32位

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

给定输入时1230,将输出0321


我刚刚看到了模数运算符的编辑...我应该删除这篇文章吗?
ace_HongKong独立2014年

7
我不认为您应该删除它,因为这是不使用它的建议,而不是一条规则:"Since this is a popularity contest, I suggest not using the modulus (%) operator in your code."
ProgramFOX 2014年

再加上那巨大的if语句实际上是ASCII艺术。
Jonathan Van Matre 2014年

4

后记

/rev{0 exch{dup 10 mod 3 -1 roll 10 mul add exch 10 idiv dup 0 eq{pop exit}if}loop}def

没有数组,没有字符串,没有变量。

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

没有mod(没有问题,只是一个捷径,所以没什么大区别):

/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

4

C#

这不使用任何字符串或数组,但是使用.NET Stack<T>类型(编辑:最初使用的模运算符;现已删除)

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

4

C

显而易见的解决方案用其他几种语言表示,不妨将其发布在C中。

打高尔夫球:

r;main(n){scanf("%d",&n);for(;n;n/=10)r=r*10+n%10;printf("%d",r);}

取消高尔夫:

#include <stdio.h>

int main()
{
     int n, r = 0;
     scanf("%d", &n);
     for(;n;n/=10)
     { 
          r = r * 10 + n % 10;
     }
     printf("%d", r);
}

编辑:刚看到模量编辑。

高尔夫球(无模):

r;main(n){scanf("%d",&n);for(;n;n/=10)r=r*10+(n-10*(n/10));printf("%d",r);}

脱胶(无模量):

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

4

爪哇

这是我想出的,没有字符串,没有数组...甚至没有变量(在Java中,我介意您):

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

编辑更易读的版本

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

请使您的代码更具可读性,这不是代码高尔夫球。谢谢。
duci9y

1
这是我的第一次尝试,我希望更新的版本更好:-)
oiZo 2014年

是的。谢谢。欢迎来到Code Golf。我也是新人 :)
duci9y

3

电源外壳

PowerShell中的快速解决方案。没有使用隐式或显式的数组或字符串。

function rev([int]$n) {
    $x = 0
    while ($n -gt 0) {
        $x = $x * 10
        $x += $n % 10
        $n = [int][math]::Floor($n / 10)
    }
    $x
}

测试:

PS > rev(13457)
75431

PS > rev(rev(13457))
13457

3

python(很容易在汇编中完成)

反转字节的位。不做其他人完全相同的事情的要点?

x = int(input("byte: "), 2)
x = ((x * 8623620610) & 1136090292240) % 1023
print("{0:b}".format(x).zfill(8))

byte: 10101010
01010101

1
样品输入产生样品输出是否可行?
duci9y

3

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

输出值

三个样品运行
在此处输入图片说明

用零测试

在此处输入图片说明

它也反转浮点数!!!

在此处输入图片说明

如果要运行此代码,请在计算机上运行它,因为它会在运行时创建一个临时文件,而且我不确定在线编译器是否会在您的计算机上创建一个临时文件


不写文件使其成为字符串吗?
duci9y

字符串是字符的组合,末尾是空字符,因此,它不是字符串,而只是字符的组合
Mukul Kumar 2014年

字符串是字符序列。抱歉,此答案不符合限制。
duci9y

您对字符串的定义是错误的,请访问此网站(cs.stmarys.ca/~porter/csc/ref/c_cpp_strings.html)并仔细阅读最后一段。字符串是以'\ 0'
Mukul Kumar 2014年

1
抱歉,您在谈论C字符串。我说的是字符串。您的答案不合格。
duci9y 2014年

2

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
}

然后:

  • reverse(12345) 输出 54321
  • reverse(3240) 输出 423
  • reverse(6342975) 输出 5792436

2

裂变

$SX/
\S?L
K\O

该程序反转输入。

$ echo -n '12345' | fsn tac.fsn
54321

1
您只是略过“在提出问题之前是否存在编程语言?” 对此进行测试。裂变看起来像是进入esolang世界的一个很酷的入口-有点像“充满了粒子物理学书籍的书架上的酸中的真菌”。真好!
Jonathan Van Matre 2014年

2

向前

我认为这与流行相反...但是使用Forth总是有创意的...

让我们创建一个新词

: REV 
  BEGIN
    S->D 10 U/
    SWAP 1 .R
  DUP 0= UNTIL 
CR ;

在这里,它使用单词U /返回余数和商,余数作为字段1个字符长的数字发送到输出,直到被除数为零。至少在将某些内容发送到视频之前,不使用任何字符串。我不使用模运算符,而是使用余数和商的整数除法。我们试试吧

12345 REV 54321
ok

ZX频谱模拟器


我在哪里可以得到该模拟器?

频谱世界这里列出了许多模拟器worldofspectrum.org/emulators.html
Mattsteel,2016年

2

图灵机代码

这里使用语法

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

在线尝试!


1

蟒蛇

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

rev(1230)321。我想应该真的给0321吗?
ace_HongKong独立2014年

错了吗 如果我们只处理数字而不是字符串,那么0321和321是等效的吧?
Jayanth Koushik 2014年

据我了解,应该是321。这个问题不允许使用字符串。所以应该是321。–
microbian

我不知道...正在等待OP的回复。我只是指出这一点,并不是说这是错误的。对困惑感到抱歉。
ace_HongKong独立2014年

我更新了问题。
duci9y 2014年

1

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

1

批量

缺少有关不使用字符串的部分-哦,很好。

@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

1

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)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.