Multiply Strings[LeetCode]

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) {
		if(num1 == "0" || num2=="0") return "0";
		int len1 = num1.size();
		int len2 = num2.size();
		int flag = 0;
		int k = 0;
		string str(len1 + len2, '0');

		for(int i=len1-1;i>=0;i--){
			int a = num1[i] - '0';
			for(int j=len2-1, k=i+len2; j>=0; j--,k--){
				int b = num2[j] - '0';
				int unit = a*b %10;
				int cur_unit = str[k] - '0';

				str[k] = (cur_unit + unit + flag)%10 + '0';
				//flag为每次进位的值,待下次计算时加入
				flag = (a*b - unit)/10 + (cur_unit + unit + flag)/10;
			}
			//处理每次循环到num2的最高位后的flag
			int m = i;
			while(flag){
				int cur = str[m] - '0';
				str[m] = (cur + flag)%10 + '0';
				flag = (cur + flag)/10;
				m--;
			}
		}
		int x = 0;
		//去除str前面的‘0’
        while (str[x] == '0')
            x++;
		str = str.substr(x,len1+len2-x);
		return str;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值