leetcode 随笔 Multiply Strings--大数相乘问题

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.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly

问题就是给你两个数,这两个数都是用string存的,然后输出他们的结果,结果也是string。

但是结果太大了,一般的int肯定是不好使了。

我们先考虑一下123*123的情况

3*123结果 放在后3位

2*123结果 放在倒数第2位到第4位

1*123结果 放在倒数第3位到第5位

首先我们要明白一个n位的数 乘以 一个m位的数,两数的结果不会超过n+m位(想想999*999<999*1000=999000)

所以我们先申请一块m+n大小的字符串res作为结果,然后给他每一位都赋值为'0'(0+48)

然后往里添数即可

class Solution {
public:
	 string multiply(string num1, string num2) {
		 if (num1 == "0" || num2 == "0") return "0";
		 int n1 = num1.size(), n2 = num2.size();
		 string res(n1 + n2, '0');
		 int jw = 0;
		 //n1*n2
		 for (int i = n1-1; i >= 0 ; i--)
		 {
			 for (int j = n2-1; j >= 0; j--)
			 {
				 int now = res[i + j + 1] - '0' + (num1[i] - '0')*(num2[j] - '0') + jw;
				 jw = now / 10;
				 res[i + j + 1] = now % 10 + '0';
			 }
			 res[i] += jw;
			 jw = 0;
		 }
		 while (res[0] == '0') res = res.substr(1);
		 return res;
	 }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值