码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Multiply Strings

时间:2015-04-24 22:47:50      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }

[LeetCode]Multiply Strings

标签:

原文地址:http://blog.csdn.net/kaitankedemao/article/details/45252057

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!