美文网首页
算法之俩个大数相乘

算法之俩个大数相乘

作者: PeterHe888 | 来源:发表于2017-09-25 10:46 被阅读13次

具体实现如下:

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

相关文章

  • 算法之俩个大数相乘

    具体实现如下: 运行结果:

  • 大数相乘之Karatsuba算法

    问题大数相乘 计算123×456,其实12345和6789就是大数。 思路 这是分治算法思想的典型体现。计算机只会...

  • 大数相乘算法

    1、计算两个大数相乘的结果。2、算法流程:(1)大数可能超出任何一种整数类型,会引发溢出问题,所以用字符串的格式存...

  • 大数相乘-算法

    参考文章 题目 思路 例如:计算98×21,步骤如下 Objective-C 版 swift 版 待更新

  • 大数相乘--golang简单实现

    大数乘法之golang实现所谓大数相乘(Multiplication algorithm),就是指数字比较大,相乘...

  • OC大数相加相乘算法

    前些天做了份笔试题,最后一道题是写一个大数相乘的算法,太久没做题了,也没有草稿纸,脑子没动起来,笔就开始天马行空了...

  • Strassen算法

    【嵌牛导读】矩阵乘法之strassen算法 【嵌牛鼻子】分治算法 矩阵相乘strassen算法 【嵌牛提问】str...

  • 大数相乘

    所谓大数相乘(Multiplication algorithm),就是指数字比较大,相乘的结果超出了基本类型的表示...

  • 大数相乘

  • 大数相乘

    两个大数相乘,这两个大数分别是a和b,现在分割成两部分,每一部分都是N位,假设是10进制的,其实对于2进制也同样适...

网友评论

      本文标题:算法之俩个大数相乘

      本文链接:https://www.haomeiwen.com/subject/mnprextx.html