Multiply Strings

来源:互联网 发布:淘宝引流手机软件 编辑:程序博客网 时间:2024/06/06 23:54

一、问题描述

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.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.

二、思路

按照乘法相乘的原则,最关键的一行代码为

int temp = (v[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
这行代码中计算了当前的两位数字相乘的结果加上进位再加上上一次循环存储的值,此时的进位表示

还有最后每行计算完都要加上额外的进位,如果没有额外进位,则carry = 0;

            v[i] += carry;

三、代码

class Solution {public:    string multiply(string num1, string num2){        string v(num1.size() + num2.size(), '0');                for(int i = num1.size() - 1; i >= 0; --i){            int carry = 0;            for(int j = num2.size() - 1; j >= 0; --j){                int temp = (v[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;                v[i + j + 1] = temp % 10 + '0';                carry = temp / 10;            }            v[i] += carry;        }        size_t start_pos = v.find_first_not_of("0");        if(string::npos != start_pos)            return v.substr(start_pos);        return "0";    }};


0 0
原创粉丝点击