Multiply Strings

来源:互联网 发布:淘宝总显示网络异常 编辑:程序博客网 时间:2024/06/16 13:38

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:    string multiply(string num1, string num2) {        string result;    int m = num1.length();    int n = num2.length();    if (num1.compare("0") == 0 || num2.compare("0") == 0)    {        return "0";    }    int offset = 0;    for (int i = m-1; i >= 0; i--)    {    string curValue;    int c = 0;    for (int j = n-1; j >= 0; j--)    {    int temp = (num2[j]-'0') * (num1[i]-'0') + c;    int val = temp % 10;    c = temp / 10;    curValue.append(1, val+'0');    }    if (c > 0)    {    curValue.append(1, c+'0');    }            if (result.length() == 0)            {                result = curValue;                continue;            }    offset++;    int len1 = result.length();    int len2 = curValue.length();    int p = offset;    int q = 0;    c = 0;    while (p < len1 && q < len2)    {    int temp = (result[p]-'0') + (curValue[q]-'0') + c;    int val = temp % 10;    c = temp / 10;    result[p] = val + '0';    p++;    q++;    }    while (q < len2)    {    int temp = (curValue[q]-'0') + c;    int val = temp % 10;    c = temp / 10;    result.append(1, val+'0');    q++;    }    if (c > 0)    {    result.append(1, c+'0');    }    }    int left = 0;     int right = result.length()-1;    while (left < right)    {    swap(result[left], result[right]);    left++;    right--;    }    return result;     }};


0 0
原创粉丝点击