LintCode 656. Big Integer multiplication

原题

LintCode 656. Big Integer multiplication

Description

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2

Example

  • The length of both num1 and num2 is < 110.
  • Both num1 and num2 contains only digits 0-9.
  • Both num1 and num2 does not contain any leading zero.
  • You must not use any built-in BigInteger library or convert the inputs to integer directly.

解题

高精度乘法

代码

class Solution {
public:
    /*
    * @param num1: a non-negative integers
    * @param num2: a non-negative integers
    * @return: return product of num1 and num2
    */
    string multiply(string &num1, string &num2) {
        // write your code here
        if (num1 == "0" || num2 == "0") return "0";
        int n = num1.size() + num2.size();
        int *res = new int[n];
        for (int i = 0; i < n; i++) res[i] = 0;
        if (num1.length() < num2.length()) swap(num1, num2);
        for (int i = num1.size() - 1; i >= 0; i--) {
            for (int j = num2.size() - 1; j >= 0; j--) {
                res[i + j + 1] += (num1[i] - '0') * (num2[j] - '0');
            }
        }
        for (int i = n - 1; i > 0; i--) {
            res[i - 1] += res[i] / 10;
            res[i] %= 10;
        }
        string ans;
        for (int i = 0; i < n; i++) {
            if (res[i] == 0 && ans.empty()) continue;
            ans += char(res[i] + '0');
        }
        return ans;
    }
};
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,774评论 5赞 6
  • 常青的藤蔓在不知不觉中枯萎了,只留下衰败的身子;老树静默地站着,仿佛看淡了这世间红尘;黄昏了,将要回巢的乌...
    0429钰薇阅读 439评论 1赞 2
  • 你知道比死更艰难的是什么?是饶恕。因为忍受长时间的痛苦后才能饶恕!——电影《不可饶恕》
    安婼蓝儿阅读 190评论 0赞 1
  • “今天是2015年最后一天,你有什么要对我说的吗?严肃一点。” “我们在一起也大半年了,认识你真好!”
    浅云兮阅读 135评论 0赞 0

友情链接更多精彩内容