[LeetCode]Multiply Strings

来源:互联网 发布:淘宝销售法则有哪些 编辑:程序博客网 时间:2024/06/05 08:07

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.

给定两个字符串表示的数,要求求这两个数的乘积,乘积用字符串表示。其中,字符串表示的数是非负数。

写的很粗糙,一点都不优雅QAQ

string multiply(string num1, string num2) {        vector<string> ans_temp;        string temp;        //先计算出num1表示的数与num2表示的数的各个位的乘积,乘积用字符串表示,保存在ans_temp中        for (int i = num2.length() - 1, count = 0; i >= 0; i--,count++){            int up = 0;            string temp;            for (int j = num1.length() - 1; j >= 0; j--){                int last = ((num2[i] - '0')*(num1[j] - '0') +up)% 10;                up = ((num2[i] - '0')*(num1[j] - '0') + up) / 10;                temp.push_back(last + '0');            }            if (up)                temp.push_back(up + '0');//最高位有进位            reverse(temp.begin(),temp.end());            for (int k = count; k > 0; k--){                temp.push_back('0');//低位补零            }            reverse(temp.begin(), temp.end());            ans_temp.push_back(temp);            temp = "";        }        int up = 0;        string ans;        int t = 0;        //求和        for (int j = 0; j < ans_temp.size(); j++){            for (int i = t; i <ans_temp[j].length(); i++){                int a = up;                for (int k = j; k < ans_temp.size(); k++){                    a += (ans_temp[k][i] - '0');                }                up = a / 10;                a = a % 10;                ans.push_back(a + '0');            }            t = ans_temp[j].length();        }        if (up){            ans.push_back(up+'0');        }        reverse(ans.begin(), ans.end());        if (ans[0] == '0')            return "0";        return ans;    }
0 0