首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算一个数字的数字差和

计算一个数字的数字差和
EN

Code Golf用户
提问于 2015-09-20 05:12:42
回答 15查看 3.5K关注 0票数 41

考虑取一些非负整数,如8675309,并计算所有相邻数字对之间差值的绝对值。

对于8675309,我们得到了|8-6| = 2|6-7| = 1|7-5| = 2|5-3| = 2|3-0| = 3|0-9| = 9。将这些结果串在一起产生另一个较小的非负整数:212239。重复这个过程会给出11016,然后是0115,按照惯例,前导零不会写成115,它变成了044,不能再缩小了。将所有这些值加起来,我们得到8675309 + 212239 + 11016 + 115 + 4 = 8898683

让我们将数字差和(或DDS)定义为重复获取一个数字的数字差异以形成一个新数字的操作,然后将所有产生的数字添加到原始数字中。

以下是对应DDS序列中的前20个值:

代码语言:javascript
复制
N   DDS(N)
0   0
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10  11
11  11
12  13
13  15
14  17
15  19
16  21
17  23
18  25
19  27

以下是前10000个值,它的图形非常奇怪:

特别是当你把它画到1000甚至100时,它看起来是一样的:

(我称它为牙医的楼梯.)

挑战

编写一个接受非负整数并打印或返回其DDS值的程序或函数。例如,如果输入是8675309,则输出应该是8898683

以字节为单位的最短代码获胜.

EN

回答 15

Code Golf用户

回答已采纳

发布于 2015-09-20 05:24:35

Pyth,17

代码语言:javascript
复制
s.ui.aM-VJjNTtJTQ

在这里试试或运行测试套房

解释:

代码语言:javascript
复制
s.u            Q   # Cumulative reduce, i.e. getting the intermediate values of each reduce
                     step and returning them as a list, then sum the list
   i ... T         # Convert the resulting list of numbers into a base 10 number
   .aM             # Get the absolute value of each element of ...
      -VJjNTtJ     # Perform vector subtraction on the lists given by
        JjNT       # assign J the number we currently have converted to its base 10 digits
            tJ     # and J[1:]. e.x. for 123 we get J = [1,2,3] then we do
                   # zip(J,J[1:]) which gives [[1,2],[2,3]] then element wise subtract
                   # to get [-1, -1]
票数 11
EN

Code Golf用户

发布于 2015-09-20 08:07:27

Python 2,73

幸运的是,我成功地避免了任何字符串操作。

代码语言:javascript
复制
t=lambda n:n>9and abs(n%10-n/10%10)+10*t(n/10)
g=lambda n:n and n+g(t(n))

g是计算答案的函数。

票数 17
EN

Code Golf用户

发布于 2015-09-20 12:13:34

Java - 300字节

金版

代码语言:javascript
复制
static Long t=new Scanner(System.in).nextLong();static char[]c=t.toString().toCharArray();public static void main(String[]z){while(c.length>1)s();System.out.print(t);}static void s(){String s="";for(int i=0;i<c.length-1;)s+=Math.abs(c[i]-c[++i]);Long a=new Long(s);t+=a;c=a.toString().toCharArray();}

Ungolfed /全版

代码语言:javascript
复制
import java.util.Scanner;

public class DigitDifference {

    static Long t = new Scanner(System.in).nextLong();
    static char[] c = t.toString().toCharArray();

    public static void main(String[] args){
        while( c.length > 1 )
            s();
        System.out.print(t);
    }

    static void s(){
        String s="";
        for(int i = 0; i < c.length-1;)
            s += Math.abs(c[i]-c[++i]);
        Long a = new Long(s);
        t += a;
        c = a.toString().toCharArray();
    }
}
票数 5
EN
页面原文内容由Code Golf提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codegolf.stackexchange.com/questions/58328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档