奇怪的求和: a+ aa + aaa + aaaa +⋯+ a ... aa

 求a+ aa + aaa + aaaa +⋯+ a ... aa, 最后一项有n个a, 例如2+22+222+2222, 15+1515+151515+15151515

我在CSDN看了不少的求和,发现用的最多的就是:

​def funny_function(a, n):
    t = a
    m = a
    for i in range(n-1):
        t = 10*t + a
        m += t
    return m

funny_function(2,4)

 

如果a是两位数,如a = 12,或者三位数甚至更多位数, 则结果不对。下面是我的代码 (python 3):

代码1: casting

def element(x, n):
    return int(str(x) * n)

def funny_function(a, n): 
    s=0
    for i in range(1, n + 1):
        s += element(a, i)
    return (s)

代码2:类似在csdn看到的方法,不过考虑到多位数

# get digit(s) of the original input, ten digit, hundred digit...
def get_digits(x):
    ds = []
    while x > 0:
        x, d = divmod(x, 10)
        ds.append(d)
    ds.reverse()
    return ds


# get element of each item
def element(x, n):
    ds = get_digits(x)
    res = 0
    for i in range(n):
        for d in ds:
            res = 10 * res + d
    return res


def funny_function(a, n):
    res = a
    for i in range(2, n + 1):
        res += element(a, i)
    return res
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值