[Leetcode]Multiply Strings

来源:互联网 发布:拍照软件 桃心 编辑:程序博客网 时间:2024/06/05 07:58

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

class Solution {public:    /*algorithm        based on standard multiply rule    */    string multiply(string num1, string num2) {            string s;            int n1=num1.size(),n2 = num2.size();            int digit,carry,k;            vector<int>line(n1*n2+1,0);            for(int i = n1-1;i >= 0;i--){                k = n1-i-1;                carry = 0;                int d1 = num1[i] - '0';                for(int j = n2-1;j >=0;j--){                    int d2 = num2[j] - '0';                    line[k] += d1*d2 + carry;                    carry = line[k]/10;                    line[k] %= 10;                    ++k;                }                if(carry > 0)line[k] = carry;            }                        k = n1*n2;            for(;line[k]==0 && k > 0;k--);            for(;k >= 0;k--)                s.append(1,line[k]+'0');                        return s;                }};



0 0
原创粉丝点击