首页 > 学院 > 开发设计 > 正文

LeetCode 43. Multiply Strings

2019-11-08 02:48:25
字体:
来源:转载
供稿:网友

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

class Solution {public:	string multiply(string num1, string num2) {		int allLen = num1.length() + num2.length();		string all(allLen,'0'); //initial		if(num1.length() > num2.length()){			string temp = num1;			num1 = num2;			num1 = temp;		}		for(int i = num1.length() - 1; i >= 0; i --){			int carry = 0,mul = 0,final = 0,index = 0;			int j = 0;			for(j = num2.length() - 1; j >= 0; j --){				mul = (num2[j] - '0') * (num1[i] - '0');				final = mul + (all[i + j + 1] - '0') + carry;				all[i + j + 1] = final % 10 + '0';				carry = final / 10;			}			while(carry != 0){				final = (all[i + index] - '0') + carry;				all[i + index] = final % 10 + '0';				carry = final / 10;				index --;			}		}		int index = 0;		while(all[index] - '0' ==0) index ++;		all = all.substr(index,allLen - index);		if(all.length() == 0) return "0";		return all;	}};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表