zoukankan      html  css  js  c++  java
  • leetcode43

    Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
    Example 1:
    Input: num1 = "2", num2 = "3"
    Output: "6"
    Example 2:
    Input: num1 = "123", num2 = "456"
    Output: "56088"
    Note:
    1. The length of both num1 and num2 is < 110.
    2. Both num1 and num2 contain only digits 0-9.
    3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
    4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

    模拟法。
    一个一个digit乘。注意一下乘出来的数字要加到哪一位即可。
    1.开结果数组int[],数组长度为两个输入字符串的长之和。(答案最长不会超过这个和)
    2.双重循环两个输入num的下标,从右往左扫(从低位开始乘)。对各为i,j下标的digit,乘积应处的位置高位在i+j, 低位在i+j+1。
    3.算出的mul答案和result里原来在这两个index的答案加一加。然后把算出来的更新答案数位分离放回原处。
    4.循环完毕把int[]转回string。注意删除前面的无效零,以及答案是0的时候也要还回去一个0.

    细节:
    1.乘法遍历digit要从string的后往前扫。
    2.mul答案加上原来占位的数变成三位数也没关系,不用更新三个地方,更新两个地方让高位变成二位数最后也还是正确的,因为那个二位数下次被拿去加的时候会加对,处理最后一次最高位的乘法的时候会把所有二位数摊平的。

    实现:

    class Solution {
        public String multiply(String num1, String num2) {
            
            int[] ans = new int[num1.length() + num2.length()];
            // 遍历要从后往前扫啊!因为后才是低位
            for (int j = num2.length() - 1; j >= 0 ; j--) {
                for (int i = num1.length() - 1; i >= 0 ; i--) {
                    int idxLow = i + j + 1;
                    int idxHigh = i + j;
                    int mul = (num2.charAt(j) - '0') * (num1.charAt(i) - '0');
                    mul = mul + ans[idxHigh] * 10 + ans[idxLow];
                    ans[idxHigh] = mul / 10;
                    ans[idxLow] = mul % 10;
                }
            }
            
            StringBuilder sb = new StringBuilder();
            int i = 0;
            while (i < ans.length && ans[i] == 0) {
                i++;
            }
            while (i < ans.length) {
                sb.append(ans[i++]);
            }
            return sb.length() == 0 ? "0" : sb.toString();
        }
    }
  • 相关阅读:
    在eclipse外边打开浏览器
    双开Eclipse
    6.5版本的CentOSLinux
    Intel x86_64 Architecture Background 3
    Java 大数、高精度模板
    Intel x86_64 Architecture Background 2
    Intel x86_64 Architecture Background 1
    Codeforces 999D Equalize the Remainders (set使用)
    Codeforces 996E Leaving the Bar (随机化)
    欧拉函数(小于或等于n的数中与n互质的数的数目)&& 欧拉函数线性筛法
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9662050.html
Copyright © 2011-2022 走看看