设为首页 加入收藏

TOP

LeetCode Multiply Strings
2015-07-20 17:12:47 来源: 作者: 【 】 浏览:2
Tags:LeetCode Multiply Strings

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) {
        reverse(num1.begin(), num1.end());
        reverse(num2.begin(), num2.end());
        int len1 = num1.size(), len2 = num2.size();

        string ans(len1+len2+1, '0');
        int tmp = 0;
        for (int i = 0; i < len1; i++) {
            int cur = num1[i] - '0';
            tmp = 0;
            for (int j = 0; j < len2; j++) {
                int a = tmp + cur * (num2[j]-'0') + (ans[i+j]-'0');
                tmp = a / 10;
                ans[i+j] = a % 10 + '0';
            }
            int idx = len2;
            while (tmp != 0) {
                int a = tmp + (ans[i+idx]-'0');
                tmp = a / 10;
                ans[i+idx] = a % 10 + '0';
                idx++;
            }
        }

        while (!ans.empty() && ans.back() == '0') 
            ans.pop_back();
        if (ans.empty()) return "0";
        reverse(ans.begin(), ans.end());
        return ans;
    }
};



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU 1070 Milk 下一篇uva 757 Gone Fishing (贪心)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·有没有哪些高效的c++ (2025-12-27 08:20:57)
·Socket 编程时 Accep (2025-12-27 08:20:54)
·计算机网络知识点总 (2025-12-27 08:20:52)
·一篇说人话的文章, (2025-12-27 07:50:09)
·Python Web框架哪家 (2025-12-27 07:50:06)