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

字符串相乘

时间:2020-03-17 19:36:26      阅读:44      评论:0      收藏:0      [点我收藏+]

标签:public   string   code   div   http   输入   color   mda   ref   

43. 字符串相乘

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

示例 1:

输入: num1 = "2", num2 = "3"
输出: "6"
示例 2:

输入: num1 = "123", num2 = "456"
输出: "56088"
说明:

num1 和 num2 的长度小于110。
num1 和 num2 只包含数字 0-9。
num1 和 num2 均不以零开头,除非是数字 0 本身。
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。

public class T43 {
    public String multiply(String num1, String num2) {
        if (num1 == null || num1.length() == 0  || num2 == null || num2.length() == 0) {
            return null;
        }
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }
        int len1 = num1.length();
        int len2 = num2.length();
        int len3 = len1 + len2;

        int[] num3 = new int[len3];
        for (int i = len1 - 1; i >= 0; i--) {
            for (int j = len2 - 1; j  >= 0; j--) {
                //注意累加——同是此位上的值,i为2j为1 和 i为1 j为2 时均会加到此位置上
                num3[i + j + 1] += (num1.charAt(i) - ‘0‘) * (num2.charAt(j) - ‘0‘);
            }
        }
        int carry = 0;
        for (int i = num3.length - 1; i >= 0; i--) {
            int temp = (num3[i] + carry) % 10;
            carry = (num3[i] + carry) / 10;
            num3[i] = temp;
        }
        int i = 0;
        String res = "";
        while (num3[i] == 0) {
            i++;
        }
        for (int j = i; j < num3.length; j++) {
            res += num3[i];
        }
        return res;
    }
}

 

字符串相乘

标签:public   string   code   div   http   输入   color   mda   ref   

原文地址:https://www.cnblogs.com/zzytxl/p/12512421.html

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