题解 | #大数乘法#

大数乘法

https://www.nowcoder.com/practice/c4c488d4d40d4c4e9824c3650f7d5571

using System;
using System.Collections.Generic;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串 第一个整数
     * @param t string字符串 第二个整数
     * @return string字符串
     */
    public string solve (string s, string t) {
        if (string.IsNullOrWhiteSpace(s) && string.IsNullOrWhiteSpace(t))
            return string.Empty;
        if (string.IsNullOrWhiteSpace(s))
            return t;
        if (string.IsNullOrWhiteSpace(t))
            return s;
        if (s == "0" || t == "0")
            return "0";
        int nLen = s.Length + t.Length;
        int[] nST = new int[nLen];
        Array.ForEach(nST, r => r = 0);
        for (int i = t.Length - 1; i >= 0; i--) {
            int nC = 0;
            for (int j = s.Length - 1; j >= 0; j--) {
                int nS, nT;
                nS = nT = 0;
                if (!int.TryParse(s[j].ToString(), out nS) ||
                        !int.TryParse(t[i].ToString(), out nT))
                    return string.Empty;

                int nSum = (nS * nT + nC + nST[(i + j + 1)]);
                nST[(i + j + 1)] = nSum % 10;
                nC = nSum / 10;
            }
            nST[i] = nC;
        }
        return string.Join("", nST).TrimStart('0');
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务