C# solution easy to understand mul + sum


  • 0
    Y
    public class Solution {
        public string Multiply(string num1, string num2) {
            string res="0";
            for(int i=num2.Length-1;i>=0;i--)
            {
                StringBuilder sb=new StringBuilder();
                string mul=multiply(num1,num2[i]);
                if(mul=="0")
                    continue;
                sb.Append(multiply(num1,num2[i]));
                for(int j=0;j<num2.Length-1-i;j++)
                {
                    sb.Append("0");
                }
                res=plus(res,sb.ToString());
            }
            return res;
        }
        
        public string plus(string s, string t)
        {
            int m=s.Length-1,n=t.Length-1;
            StringBuilder resSb=new StringBuilder();
            int caOn=0;
            while(m>=0 || n>=0)
            {
                int sNu=m>-1 ? int.Parse(s[m].ToString()) : 0;
                int tNu=n>-1 ? int.Parse(t[n].ToString()) : 0;
                int sum = sNu + tNu + caOn;
                if(sum>9)
                {
                    sum -= 10;
                    caOn=1;
                }
                else
                    caOn=0;
                resSb.Insert(0,sum.ToString());
                m--;
                n--;
            }
            if(caOn==1)
                resSb.Insert(0,"1");
            return resSb.ToString();
        }
        
        public string multiply(string s, char chT)
        {
            string t=chT.ToString();
            StringBuilder sb=new StringBuilder();
            if(t=="0")
                return "0";
            int caOn=0;
            for(int i=s.Length-1;i>=0;i--)
            {
                int sum = int.Parse(s[i].ToString())*int.Parse(t)+caOn;
                sb.Insert(0,(sum%10).ToString());
                caOn = sum/10;
            }
            if(caOn>0)
                sb.Insert(0,caOn.ToString());
            return sb.ToString();
        }
    }

Log in to reply
 

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