【LeetCode】C# 43、Multiply Strings

来源:互联网 发布:淘宝店铺分类模板代码 编辑:程序博客网 时间:2024/06/05 02:51

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.

计算两个字符串表示的非负大整数的乘积,结果仍然用字符串表示。
思路:主要是运用num1[i] - '0'来把具体char转化为int。然后定义数组pos来保存位乘的结果后转化为string。

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[i] - '0') * (num2[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();        foreach(int p in pos)            if(!(sb.Length == 0 && p == 0))                 sb.Append(p);        return sb.Length == 0 ? "0" : sb.ToString();    }}