码迷,mamicode.com
首页 > 其他好文 > 详细

大数乘法

时间:2017-01-21 00:32:01      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:index   --   length   color   ret   tostring   app   pen   logs   

public static String mul(String str1, String str2)
    {
        int minLength = -1;
        int maxLength = -1;
        if (str1.length() > str2.length())
        {
            minLength = str2.length();
            maxLength = str1.length();
        }
        else
        {
            minLength = str1.length();
            maxLength = str2.length();
            String temp = str1;
            str1 = str2;
            str2 = temp;
        }
        int[] cc = new int[maxLength + minLength];
        int maxIndex = -1;
        for (int i = minLength - 1; i >= 0; i--)
        {
            char c2 = str2.charAt(i);
            int cIndex = minLength - 1 - i;
            int dx = 0;
            for (int j = maxLength - 1; j >= 0; j--)
            {
                cc[cIndex] = (str1.charAt(j) - 0) * (c2 - 0) + dx
                        + cc[cIndex];
                dx = cc[cIndex] / 10;
                cc[cIndex] = cc[cIndex] % 10;
                cIndex++;
            }
            if (maxIndex < cIndex)
            {
                maxIndex = cIndex;
            }
            cIndex = maxIndex;
            if (dx != 0)
            {
                while (dx != 0)
                {
                    cc[cIndex] = cc[cIndex] + dx;
                    dx = cc[cIndex] / 10;
                    cc[cIndex] = cc[cIndex] % 10;
                    cIndex++;
                }
                maxIndex = cIndex;
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = maxIndex - 1; i >= 0; i--)
        {
            if(cc[i]==0  && i==maxIndex-1)
            {
                return "0";
            }
            sb.append((char) (cc[i] + 0));
        }
        return sb.toString();
    }

 

大数乘法

标签:index   --   length   color   ret   tostring   app   pen   logs   

原文地址:http://www.cnblogs.com/shuiyonglewodezzzzz/p/6329700.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!