AcWing793高精度乘法

AcWing793高精度乘法

题目:

在这里插入图片描述

题目大意:

​ 如图所示。

数据范围:

如图所示

思路:

​ 假设有一个数A(a3 a2 a1),分别为A的百位,十位,个位。一个数B,我们读入之后为了方便从下标为0计算将A变为a1 a2 a3。

设进位为 t ,初始 t = 0,则 C = A * B 的个位为 (t + (a1 * B)) % 10, 对下一位的进位为 t = (t + (a1 * B)) / 10。

所以可以使用t, t += a1 * B,则C的该位为 t % 10, 对下一位的进位为 t = t / 10。

最后当 A 遍历完之后,要处理完进位t。

注意 B 为 0 的情况。

代码:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static List<Integer> multiply(List<Integer> numa, int numb){
        List<Integer> numc = new ArrayList<>();
        if (numb == 0)
        {
            numc.add(0);
            return numc;
        }
        for (int i = 0, t = 0; i < numa.size() || t != 0; i ++ ){
            if (i < numa.size()){
                t += numa.get(i) * numb;
            }
            numc.add(t % 10);
            t /= 10;
        }
        return numc;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String a = scanner.next();
        int numb = scanner.nextInt();
        List<Integer> numa = new ArrayList<>();
        for (int i = a.length() - 1; i >= 0; i -- ){
            numa.add(a.charAt(i) - '0');
        }
        List<Integer> numc = multiply(numa, numb);
        for (int i = numc.size() - 1; i >= 0; i -- ){
            System.out.print(numc.get(i));
        }
    }

}

时空复杂度分析等:

  • 时间复杂度 : O(n)

  • 空间复杂度 : O(n)

题目链接:

793. 高精度乘法 - AcWing题库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值