算法之俩个大数相乘

具体实现如下:

public class LargeNumMultiply {
    public static void main(String[] agrs) {
        long timeStart = System.currentTimeMillis();
        System.out.println("result=" + getResult("99", "19"));
        System.out.println("result=" + getResult("99", "99"));
        System.out.println("result=" + getResult("123456789", "987654321"));
        System.out.println("result=" + getResult("12345678987654321", "98765432123456789"));
        System.out.println("time=" + (System.currentTimeMillis() - timeStart));

    }
    
    public static String getResult(String bigIntA, String bigIntB) {
        int maxLength = bigIntA.length() + bigIntB.length();
        int[] result = new int[maxLength];
        int[] aInts = new int[bigIntA.length()];
        int[] bInts = new int[bigIntB.length()];
        
        for(int i=0; i<bigIntA.length(); i++) {
            aInts[i] = bigIntA.charAt(i) - '0'; //bigIntA 字符转换为数字存到数组
        } 
        for(int i=0; i<bigIntB.length(); i++) {
            bInts[i] = bigIntB.charAt(i) - '0'; //bigIntB 字符转换为数字存到数组
        }
        
        int curr; // 记录当前正在计算的位置,倒序
        int x, y, z; // 记录个位,十位
        
        for(int i=bigIntB.length() -1; i>= 0; i--) {
            curr = bigIntA.length() + i;
            for(int j=bigIntA.length()-1; j>=0; j--) {
                z = bInts[i] * aInts[j] + result[curr]; // 乘积并加上上一次计算的进位
                x = z % 10; // 个位
                y = z / 10; // 十位
                result[curr] = x; // 计算存到数组c中
                result[curr -1]+= y; // curr - 表示前一位,这里是进位的意思
                curr--;
            }
        }
        
        int t = 0;
        for(; t<maxLength; t++) {
            if(result[t] != 0)
                break; // 最前面的0都不输出
        }
        StringBuilder builder = new StringBuilder();
        if(t == maxLength) {
            builder.append('0');
        } else {
            for(int i = t; i< maxLength; i++) {
                builder.append(result[i]);
            }
        }
        return builder.toString();
    }
}

运行结果:

俩个大数相乘.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,595评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,993评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,779评论 18 399
  • 阳泉煤业集团兴峪煤业有限责任公司,税号:91140000701079591G,地址:盂县路家村镇石坡峪村,电话03...
    登徒浪子_阅读 302评论 0 0
  • 我一点一点走近你 然后静静地看着你 遥遥相望,你的模样 选取了你最娇艳的模样 我竟,深深的沉迷了 一步一步,我该走...
    南城花落阅读 380评论 5 2