zoukankan      html  css  js  c++  java
  • 43. Multiply Strings

    题目描述:

    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.

    解题思路:

    从num1 和 num2的长度可以看出,直接将字符串转化成数字有溢出的可能,而且note4中也提到了不允许直接转。

    我们可以将乘法分步来看:

    例如 123 * 456:

    实际上是用了错位相减法。

    两个数相乘,其长度最多是原来长度的两倍,所以我们可以够早一个存储数组来存储当前位的数。

    注意的是当前位下标的计算:

    int idx = total_size - (len1 - i- 1) - (len2 - j -1);

    减的是i和j与最初值的变化量。

    更新存储数组的的值:

          store[idx] += temp;
              store[idx - 1] += (store[idx]/10);
              store[idx] %= 10;

    要对最终的值算进位并加到前一位

    在求余就是当前值。

    要记得判断首位是不是0!

    代码:

    class Solution {
    public:
        string multiply(string num1, string num2) {
            int len1 = num1.size();
            int len2 = num2.size();
            if(num2 == "0" || num1 == "0")
                return "0";
            string ret;
            vector<int> store(len1+len2, 0);
            int total_size = len1 + len2 -1;
            for(int i = len1 - 1; i > -1; i--){
                for(int j = len2 - 1; j > -1; j--){
                    int n1 = num1[i]-'0';
                    int n2 = num2[j]-'0';
                    int temp = n1 * n2;
                    int idx = total_size - (len1 - i- 1) - (len2 - j -1);
                    store[idx] += temp;
                    store[idx - 1] += (store[idx]/10);
                    store[idx] %= 10;
                }
            }
            int i = 0;
            while(store[i] == 0)
                i++;
            for(; i <= total_size; i++){
                char c = store[i]+'0';
                ret.push_back(c);
            }
            return ret;
        }
    };
  • 相关阅读:
    js 学习之路8:for循环
    js 学习之路7:switch/case语句的使用
    Python语法速查: 16. 时间日期处理
    初级模拟电路:4-1 BJT交流分析概述
    初级模拟电路:3-11 BJT实现电流源
    Python语法速查: 7. 函数基础
    初级模拟电路:3-10 BJT实现开关电路
    初级模拟电路:3-9 BJT三极管实现逻辑门
    Python语法速查: 6. 循环与迭代
    初级模拟电路:3-8 BJT数据规格书(直流部分)
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9158326.html
Copyright © 2011-2022 走看看