easy C# solution using stack


  • 0
    K
    public class Solution {
        public string AddStrings(string num1, string num2) {
            int sum = 0;
            int rem = 0;
            int val = 0;   
            int len1 = num1.Length;
            int len2 = num2.Length;
            int maxlen = Math.Max(num1.Length,num2.Length);
            Stack q = new Stack();
            string s = String.Empty;
            for (int i=0;i<maxlen;i++) {
                sum = 0;
                if (i<len1)
                    sum += (int)Char.GetNumericValue(num1[len1-1-i]);
                if (i<len2)
                    sum += (int)Char.GetNumericValue(num2[len2-1-i]);
                sum += rem;
                if (sum >= 10) {
                    rem = 1;
                    val = sum-10;
                }
                else {
                    rem = 0;
                    val = sum;
                }
                q.Push(val);
            }
            if (rem > 0)
                q.Push(rem);
            while (q.Count>0) {
                int element = (int)q.Pop();
                s = s+""+element;
            }
            return s;
        }
    }
    

Log in to reply
 

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