leetcode multiply-strings
Posted zhibin123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode multiply-strings相关的知识,希望对你有一定的参考价值。
题干:
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3" Output: "6"
Example 2:
Input: num1 = "123", num2 = "456" Output: "56088"
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contain only digits0-9
. - Both
num1
andnum2
do not contain any leading zero, except the number 0 itself. - You must not use any built-in BigInteger library or convert the inputs to integerdirectly.
大意:
大整数乘法
输入:string
输出:string
思路:
1、计算乘积中对应位的结果。不考虑进位时,根据乘数位数可以确定乘积位数,乘积对应位置的数是由乘数确定位置的数确定。如num1*num2,结果会有len1-1+len2-1+1位。计算时:
R[len - i - j]+=((num1[i]-‘0‘)*(num2[j]-‘0‘));
2、处理进位。乘积计算完后将进位由低位开始向高位进位调整每位符合十进制数
3、去掉前导零。
class Solution { public: string multiply(string num1, string num2) { int len1=num1.length(),len2=num2.length(); int len = len1+len2-2; int C = 0; int R[220]={0}; string ans;//对应位乘 for(int i = 0 ; i < len1;i++){ for(int j = 0;j < len2;j++){ R[len - i - j]+=((num1[i]-‘0‘)*(num2[j]-‘0‘)); } } //处理进位 for(int i = 0 ; i < len1+len2 ;i++){ R[i] += C; C = R[i]/10; R[i] %= 10; } //处理前导0 int k = len1+len2; while(!R[k]){ k--; if(k<0) return "0"; } //压入string返回 for(int i = k ; i >= 0;i--){ ans.push_back(R[i]+‘0‘); } return ans; } };
以上是关于leetcode multiply-strings的主要内容,如果未能解决你的问题,请参考以下文章