Monday, January 18, 2021

Add two strings

Problem: Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. It is given that length of strings can be very large, both num1 and num2 does not contain any leading zero.

Example:

Input: num1 = "9", num2 = "97"
Output: "106"


Approach: Nothing to explain, just look at the implementation.


Implementation in C#:

        public static string AddStrings(string num1, string num2)

        {

            char[] result = new char[Math.Max(num1.Length, num2.Length) + 1];

            int i = num1.Length - 1, j = num2.Length - 1, k = result.Length - 1, proxy = 0; 

            while(i >= 0 && j >= 0)

            {

                int sum = (num1[i--] - '0') + (num2[j--] - '0') + proxy;

                proxy = sum / 10;

                sum %= 10;

                result[k--] = (char)(sum + '0');

            }

            if (i >= 0)

            {

                AddStringWithProxy(num1, i, result, k, proxy);

            }

            else if (j >= 0)

            {

                AddStringWithProxy(num2, j, result, k, proxy);

            }

            else if (proxy > 0)

            {

                result[k] = (char)(proxy + '0');

            }

            return result[0] == 0 ? new string(result, 1, result.Length - 1) : new string(result);

        }


        private static void AddStringWithProxy(string s, int sIndex, char[] result, int rIndex, int proxy)

        {

            while(sIndex >= 0)

            {

                int sum = (s[sIndex--] - '0') + proxy;

                proxy = sum / 10;

                sum %= 10;

                result[rIndex--] = (char)(sum + '0');

            }

            if (proxy > 0)

            {

                result[rIndex] = (char)(proxy + '0');

            }

        }


Complexity: O(n) where n is the maximum of num1's length and num2's length.

No comments:

Post a Comment