LC 43. Multiply Strings 大数乘法 / 字符串操作 / 细节:“000”要转化为“0”输出

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

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.

题目就是让实现一个大数的乘法。这道题建立在大数加法之上。分析乘法的原理,对于 a * b,最基本的就是 a 以 b 中从右往左乘的每一个单个数字,并将结果乘以适当的 10^n,然后将得到的所有数相加。因此需要两个辅助函数,一个支持大数的加法,另一个支持一个很长的数乘以一个一位数并乘以10^n。非常简单,直接上代码:

string add(string num1, string num2) {
    string res;
    int i = (int)num1.length() - 1;
    int j = (int)num2.length() - 1;
    int a, b, sum, flag = 0;
    while(i > -1 || j > -1 || flag) {
        a = i > -1 ? num1[i] - '0' : 0;
        b = j > -1 ? num2[j] - '0' : 0;
        sum = a + b + flag;
        flag = sum > 9 ? 1 : 0;
        res = (char)(sum % 10 + '0') + res;
        i--;
        j--;
    }
    return res;
}
string multiplyWithOneDigit(string longNum, int oneNum, int pos) {
    int i, flag = 0;
    string res;
    int product;
    i = (int)longNum.length() - 1;
    while (i > -1 || flag) {
        product = i > -1 ? oneNum * (longNum[i] - '0') + flag : flag;
        flag = product > 9 ? product / 10 : 0;
        res = (char)(product % 10 + '0') + res;
        i--;
    }
    while (pos > 0) {
        res += '0';
        pos--;
    }
    return res[0] == '0' ? "0" : res;
}
string multiply(string num1, string num2) {
    string res="0";
    int n = (int)num2.length();
    for(int i = n - 1; i >= 0; i--) {
        string product = multiplyWithOneDigit(num1, num2[i] - '0', n - i -1);
        res = add(res, product);
    }
    return res;
}

唯一需要注意的一点也是我唯一一个第一次提交没有AC的test case,就是一个数乘以0的情况。例如999 * 0第一次返回000了。问题出在multiplyWithOneDigit()这个函数上,因为一开始没有

return res[0] == '0' ? "0" : res;

这个处理,导致

res = (char)(product % 10 + '0') + res;
产生的字符串在结果为零的时候不能发现“0000...00”其实必须表示成“0”。也正是因为这个小细节我才为了这么简单的题目专门写了这一篇记录下来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值