Time - O(nm) ; Space - O(n+m) ; C#


  • 0
    S
    public class Solution {
        public string Multiply(string num1, string num2) {
            var res = new int[num1.Length + num2.Length];
            
            var t = num2.ToCharArray();
            Array.Reverse(t);
            num2 = new string(t);
            
            t = num1.ToCharArray();
            Array.Reverse(t);
            num1 = new string(t);
            
            
            int j = 0, i = 0, mulc = 0, addc = 0;
            foreach(var co in num2)
            {
                i = j; addc = 0; mulc = 0;
                foreach(var ci in num1)
                {
                    int d = (((co - '0') * (ci - '0')) + mulc);
                    mulc = d/10;
                    int r = d % 10;
                    
                    int tmp = res[i] + r + addc;
                    addc = tmp/10;
                    res[i] = tmp % 10;
                    i++;
                }
                res[i] = mulc + addc;
                j++;
            }
            res[i] = mulc + addc;
            
            if(Array.Exists(res, x => x != 0))
            {
                Array.Reverse(res);
                return string.Join("", res).TrimStart('0');        
            }
            
            return "0";
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.