一个简单实现的字符串数字乘法。


public class multiply {
    public static void main(String[] args) {
        String result = "1";
        //阶乘
        for(int i = 1; i <= 1493; i++)
        {
            result = multiString(result,String.valueOf(i));
        }
        System.out.println(result);
    }

    /**
     * 字符串乘法
     */
    public static String multiString(String m1, String m2)
    {
        String result = null;

        //数字1,2长度
        int lm1 = m1.length();
        int lm2 = m2.length();

        //结果最大长度
        int lres = lm1 + lm2 + 1;

        //结果数组
        int[] intres = new int[lres];
        int count = 0;
        for(int i1 = lm1 - 1; i1 >=0; i1--)
        {
            for(int i2 = lm2 - 1; i2 >=0; i2--)
            {
                int t = (int)(m1.charAt(i1) - 48) * (int)(m2.charAt(i2) - 48);

                //获取到当前要加的位置。
                count = lm2 - 1 - i2 + (lm1 - 1 - i1);

                //t必然为2位数。
                int t0 = t % 10;
                int t1 = t / 10;
                int jinwei = 0;

                //将新的结果加到已生成的结果上去
                intres[count] = t0 + intres[count];
                jinwei = intres[count] / 10;
                intres[count] = intres[count] % 10;

                count++;
                intres[count] = t1 + intres[count] + jinwei;

                //整理进位
                while(intres[count] / 10 > 0)
                {
                    jinwei = intres[count] / 10;
                    intres[count] = intres[count] % 10;
                    count++;
                    intres[count] = intres[count] + jinwei;
                }
            }
        }


        StringBuffer sbres = new StringBuffer();
        //是否去除0的标识
        int flag = 1;
        for(int i = lres - 1; i >= 0; i--)
        {
            // 去除开头的0;
            if(intres[i] == 0 && flag == 1)
            {
                continue;
            }
            //不再去除之后的0
            flag = 0;

            //将数组转化为String
            sbres.append(intres[i]);
        }

        result = sbres.toString();

        return result;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值