leetcode题目例题解析(六)

leetcode题目例题解析(六)

Multiply Strings

题目描述:

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

Note:
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.

题意解析:

这道题的主要要求是求两个用字符串表示的大数的乘积,并把结果也用字符串表示出来

解题思路:

这里有一个思路就是,两个数分别为mn位,则两个数的乘积为m+n,m+n-1或者1位(其中一个数是0),我在这里解题的思路是,先不考虑进位,第一个数的k位和第二个数的l位的乘积先保存在结果的第k+l-1位,让两个数的每一位两两相乘,最后再从最低位到高位进位。

代码:

class Solution {
public:
  string multiply(string num1, string num2) {
    int ans[221];
    string res;
    for (int i = 0; i < 221; i++)
      ans[i] = 0;
    int a = num1.size();
    int b = num2.size();
    int k = 0;
    //其中一个数是0,则直接返回0
    if (a == 1&&num1[0] == '0'||b == 1&&num2[0] == '0')
      return "0";
    for (int i = 0; i < a; i++) {
      for (int j = 0; j < b; j++) {
      //这里注意把字符转换成数字
        ans[i+j] += (num1[i] - '0')*(num2[j] - '0');
      }
    }
    int temp[221];
    //两个循环进行数组的翻转,上面得到的是从高位到低位的数组翻转之后方便进位
    for (int i = 0; i < a + b - 1; i++) {
      temp[a + b - i - 2] = ans[i];
    }
    for (int i = 0; i < a + b - 1; i++) {
      ans[i] = temp[i];
    }
    //进位,每一位保留个位数,大于个位的进到高一位
    for (int i = 0; i < a + b; i++) {
      ans[i+1] += ans[i]/10;
      ans[i] = ans[i]%10;
    }
    int s;
    //判断结果是m+n位还是m+n-1位,上面已经排除了0的情况
    if (ans[a + b - 1] != 0) {
      s = a + b;
    } else {
      s = a + b - 1;
    }
    for (int i = s - 1; i >= 0; i--) {
      res += (ans[i] + '0');//数字转换成字符
    }
    return res;
  }
};

原题目链接:
https://leetcode.com/problems/multiply-strings/description/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值