欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

计算--字符串相乘

程序员文章站 2022-07-10 17:26:29
LeetCode刷题记6643. 字符串相乘题目class Solution { public String multiply(String num1, String num2) { List> list = new ArrayList(); int max = 0; for (int i = num1.length() - 1; i >= 0; i --) {...

LeetCode刷题记66

43. 字符串相乘

题目
计算--字符串相乘

class Solution {
    public String multiply(String num1, String num2) {
        List<List<Integer>> list = new ArrayList();
        int max = 0;
        for (int i = num1.length() - 1; i >= 0; i --) {
            List tmp = new ArrayList<Integer>();
            for (int j = 0; j < num1.length() - 1 - i; j ++) {
                tmp.add(0);
            }
            int f = 0;
            for (int j = num2.length() - 1; j >= 0; j--) {
                int n1 = num1.charAt(i) - '0';
                int n2 = num2.charAt(j) - '0';
                int num = n1 * n2 + f;
                f = num / 10;
                num %= 10;
                tmp.add(num);
            }
            if (f > 0) tmp.add(f);
            max = Math.max(max, tmp.size());
            list.add(tmp);
        }
        // System.out.println(num1.length());
        StringBuffer ans = new StringBuffer();
        int f = 0;
        for (int i = 0; i < max; i ++) {
            int sum = f;
            for (int j = 0; j < list.size(); j ++) {
                List<Integer> tmp = list.get(j);
                if (tmp.size() > i) sum += tmp.get(i);
            }
            f = sum / 10;
            sum = sum % 10;
            ans.append(sum + "");
        }
        if (f > 0) ans.append(f + "");
        int i = ans.length() - 1;
        for (;i >= 0; i --) {
            if (ans.charAt(i) != '0') {
                break; 
            }
        }
        if (i == -1) return "0";
        ans.delete(i + 1, ans.length());
        return ans.reverse().toString();
    }
}

3/5
66/150

本文地址:https://blog.csdn.net/weixin_44013557/article/details/110245350