算法题:求s=a+aa+aaa+aaaa+aa…a的值

题目:

求s=a+aa+aaa+aaaa+aa…a的值,其中a是一个数字。
而aa…a 的最大长度是n

思路:

我们假设a 就是那个数字(1 ~ 9) , 最大长度是n

无非就是求下面的公式的值
∑ i = 1 n x n \sum_{i=1}^nx_n i=1nxn = x 1 + x 2 + x 3 . . . + x n x_1 + x_2 +x_3... +x_n x1+x2+x3...+xn

其中
x n x_n xn = a a a . . . a ⏟ n 个 \underbrace{aaa...a}_{n个} n aaa...a

其实再分析下
x n x_n xn = a a a . . . a ⏟ n 个 \underbrace{aaa...a}_{n个} n aaa...a = a ∗ 1 0 n − 1 a * 10^{n-1} a10n1 + a ∗ 1 0 n − 2 a * 10^{n-2} a10n2 + … + a ∗ 1 0 0 a * 10^{0} a100

有了上面这个公式, 解题思路就不难了

import math


def get_sum_aaaa(a: int, n: int):
    """
    :param a: the number, 1 to 9
    :param n: the number of elements of the sum list
    :return: the sum of the int list
    """

    sum_v = 0
    for i in range(1, n + 1):  # for range(1,5) means 1, 2 , 3, 4 but 5 is excluded
        sum_v = sum_v + x(a, i)
    return sum_v


def x(a: int, n: int):
    """
    :param a: the number, 1 to 9
    :param n: the length of aaaa...a
    :return: the value of aaaa...a
    """
    x_value = 0
    for i in range(0, n):
        x_value = x_value + a * math.pow(10, i)
    return int(x_value)


if __name__ == '__main__':
    print("Sum of 2 + 22 + 222 + 222..2 n=10 is {}".format(get_sum_aaaa(2, 10)))

用了双重循环, O ( n 2 ) O({n^2}) O(n2)的时间复杂度并不好

另1个思路:

x n x_n xn = a a a . . . a ⏟ n 个 \underbrace{aaa...a}_{n个} n aaa...a = a ∗ 1 0 n − 1 a * 10^{n-1} a10n1 + a ∗ 1 0 n − 2 a * 10^{n-2} a10n2 + … + a ∗ 1 0 0 a * 10^{0} a100

在上面的数列中中, X n X_n Xn = X ( n − 1 ) X_{(n-1)} X(n1) * 10 + a
也就是将我们可以从前一项可以方便推导出后一项的值。

java 代码:

public class SumAAA {
    public static void main(String[] args) {
       System.out.println(MessageFormat.format("Sum of 2 + 22 + 222 + 222..2 n=10 is {0}", new SumAAAUitl().getSum(2,10)));
    }

}

class SumAAAUitl{
    /**
     * 
     * @param a  the number, 1 to 9
     * @param n  the number of elements of the sum list
     * @return the sum of the int list
     */
    public Long getSum(int a, int n){
        Long sum = 0L;
        Long x = 0L;

        for (int i=1; i<=n; i++){
            x = x * 10 + a; // X(n) = X(n-1) * 10 + a
            sum += x;
        }
        return sum;
    }
}

时间复杂度降为 O ( n ) O(n) O(n)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nvd11

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值