LeetCode 43. Multiply Strings

来源:互联网 发布:淘宝童装店铺简介 编辑:程序博客网 时间:2024/06/16 11:53

43. Multiply Strings

Description
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

Analysis
这道题的意思就是返回两个用字符串表示的整数的乘积。
我采取的做法是用一个整型数组将每一位的字符串数组中的数字乘积记录下来,值得注意的是字符串的第一位是最高位,所以记录时应该是反过来记录的。当记录完数组后,应该开始处理进位,即将整形数组中的每一个数中如果大于10则进位,留下余数。之后是处理前导位0。
最后就是将整型数组变回字符串,再次注意字符串的第一位是最高位,所以应该反过来转换。

Code

class Solution {public:    string multiply(string num1, string num2) {        //if(num1=="0"&&num2=="0") return "0";        int len1,len2;        len1 = num1.size();        len2 = num2.size();        int res[len1+len2];        for(int i = 0 ; i < len1+len2;++i){            res[i] = 0;        }        int k = len1+len2-2;        for(int i = 0 ; i < len1;++i){            for(int j = 0 ; j <len2;++j){                res[k-i-j] += (num1[i] - '0') * (num2[j] - '0');            }        }        int a = 0;        for(int i = 0;i<len1+len2;++i){            res[i] += a;            a = res[i]/10 ;            res[i] %= 10;        }         int index = len1+len2-1;         while(res[index] == 0){            index--;            if(index<0) return "0";         }          string s;         for(int i = index;i>=0;--i){            s.push_back(res[i]+'0');         }        return s;    }};
0 0