码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode multiply-strings

时间:2019-02-06 09:12:42      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:class   product   not   res   present   整数   direct   self   als   

题干:

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:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contain only digits 0-9.
  3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  4. 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

标签:class   product   not   res   present   整数   direct   self   als   

原文地址:https://www.cnblogs.com/zhibin123/p/10353345.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!