LeetCode-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.

解题思路:1 两个数相乘,得到结果最大长度为两个数位数之和。

        2 num1中的i 位和 num2中的j位相乘,其结果在最终结果中所属位置为 i+j和i+j+1。

                  3 注意细节,例如进位等。

    string multiply(string num1, string num2) {
        if(num1.size()==0 || num2.size()==0) return "0";
        string sum(num1.size()+num2.size(),'0');
        for(int i = num1.size()-1; i >=0; i--){
            for(int j = num2.size()-1; j>=0; j--){
                int temp = (num1[i] -'0') * (num2[j] - '0');
                temp += sum[i+j+1] - '0';
                sum[i+j+1] = temp%10 + '0';
                sum[i+j] += temp/10;
                
            }
        }
        int index = sum.find_first_not_of('0');
        if(string::npos != index)
            return sum.substr(index);
        return "0";
    }

 

posted on 2019-01-29 15:32  无名路人甲  阅读(72)  评论(0)    收藏  举报