43. Multiply Strings

来源:互联网 发布:筑巢软件骗局 编辑:程序博客网 时间:2024/06/05 23:43

题目:

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.

题意:

以字符串的形式给出两个整数,同样以字符串的形式返回两个字符串的乘积;

note:

1、这些数字都可以任意大并且是非负的;

2、不允许将输入的字符串转化为整数;

3、不允许使用内部库函数,例如BigInteger。


思路:转载地址:https://leetcode.com/discuss/71593/easiest-java-solution-with-graph-explanation

根据基本乘法运算规则,从右到左将每一个数位依次对应相乘,之后相加起来。

`num1[i] * num2[j]` will be placed at indices `[i + j`, `i + j + 1]`


代码:java版:10ms

public class Solution {    public String multiply(String num1, String num2) {                int m = num1.length(), n = num2.length();        int[] pos = new int[m+n];                for (int i=m-1; i>=0; i--) {            for (int j=n-1; j>=0; j--) {                int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');                int p1 = i+j, p2 = i+j+1;                int sum = mul + pos[p2];                                pos[p1] += sum/10;                pos[p2] = (sum)%10;            }        }                StringBuilder sb = new StringBuilder();        for (int p : pos) {            if (!(sb.length() == 0 && p == 0)) {                sb.append(p);            }        }        return sb.length() == 0 ? "0" : sb.toString();    }}
代码:C++版:8ms

class Solution {public:    string multiply(string num1, string num2) {                string sum(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 tmp = (sum[i+j+1]-'0') + (num1[i] - '0') * (num2[j] - '0') + carry;                sum[i+j+1] = tmp % 10 + '0';                carry = tmp / 10;            }            sum[i] += carry;        }                size_t startpos = sum.find_first_not_of("0");        if (string::npos != startpos) {            return sum.substr(startpos);        }        return "0";    }};

0 0
原创粉丝点击