[algorithm thousand question case] daily LeetCode punch in - 75. String addition

Keywords: Algorithm leetcode

πŸ“’ preface

πŸš€ Algorithm problem πŸš€
  • 🌲 Punching out an algorithm problem every day is not only a learning process, but also a sharing process 😜
  • 🌲 Tip: the problem-solving programming languages in this column are C# and Java
  • 🌲 To maintain a state of learning every day, let's work together to become the great God of algorithm 🧐!
  • 🌲 Today is the 75th day of punching out the force deduction algorithm 🎈!
πŸš€ Algorithm problem πŸš€

🌲 Example of original question: String addition

Given two non negative integers num1 and num2 in string form, calculate their sum and return them in string form as well.

You cannot use any built-in library for handling large integers (such as BigInteger), nor can you directly convert the input string to integer form.

Example 1:

Input: num1 = "11", num2 = "123"
Output:"134"

Example 2:

Input: num1 = "456", num2 = "77"
Output:"533"

Example 3:

Input: num1 = "0", num2 = "0"
Output:"0"

Tips:

  • 1 <= num1.length, num2.length <= 104
  • Both num1 and num2 contain only the numbers 0-9
  • Neither num1 nor num2 contains any leading zeros

🌻 C# method: sort traversal

  • Simulate manual calculation. After right alignment, calculate from back to front
  • After the simulation, we get the character array, which is the sum of the two strings

code:

public class Solution {
        public string AddStrings(string num1, string num2)
        {
            var numArray = GetNumArray();
            var forReturnArray = new char[Math.Max(num1.Length, num2.Length) + 1];
            var oneIndex = num1.Length - 1;
            var twoIndex = num2.Length - 1;
            var arrayIndex = forReturnArray.Length - 1;
            var initNum = 0;
            while (oneIndex >= 0 || twoIndex >= 0)
            {
                var oneNum = 0;
                if (oneIndex >= 0)
                    oneNum = num1[oneIndex--] - '0';

                var twoNum = 0;
                if (twoIndex >= 0)
                    twoNum = num2[twoIndex--] - '0';

                var sumTemp = initNum + oneNum + twoNum;
                forReturnArray[arrayIndex--] = numArray[sumTemp % 10];
                initNum = sumTemp / 10;
            }

            if (initNum > 0)
            {
                forReturnArray[arrayIndex] = numArray[initNum];
                return new string(forReturnArray);
            }

            return new string(forReturnArray.Skip(1).ToArray());
        }

        private char[] GetNumArray()
        {
            var numArray = new char[10];
            for (var i = '0'; i <= '9'; i++)
                numArray[i - '0'] = i;

            return numArray;
        }
}

results of enforcement

adopt
 Execution time: 88 ms,At all Java  Defeated 44 in submission.50%User
 Memory consumption: 37.4 MB,At all Java Defeated 38 in submission.90%User

🌻 Java methods: counting

Train of thought analysis
This problem only needs to simulate the process of "vertical addition" for two large integers.

  • Vertical addition is the method of adding two integers commonly used in our daily study and life. Recall our operation of adding two integers on paper. Is it right to align the same digits and add them bit by bit from low to high as shown in the following figure? If the sum of the current bit exceeds 10, move one bit to the high bit?
  • So we just need to write this process in code.

  • The specific implementation is not complicated. We define two pointers i and j to point to the end of num1 , and num2 , respectively, that is, the lowest bit. At the same time, we define a variable add to maintain whether there is carry at present, and then add bit by bit from the end to the beginning.
  • You may wonder how to deal with the difference of two digits. Here, we uniformly return 0 when the current subscript of the pointer is negative, which is equivalent to the zero filling operation for the number with short digits. In this way, we can eliminate the treatment of different digits of two digits. See the following code for details.

code:

class Solution {
    public String addStrings(String num1, String num2) {
        int i = num1.length() - 1, j = num2.length() - 1, add = 0;
        StringBuffer ans = new StringBuffer();
        while (i >= 0 || j >= 0 || add != 0) {
            int x = i >= 0 ? num1.charAt(i) - '0' : 0;
            int y = j >= 0 ? num2.charAt(j) - '0' : 0;
            int result = x + y + add;
            ans.append(result % 10);
            add = result / 10;
            i--;
            j--;
        }
        // After the calculation, the answer needs to be turned over
        ans.reverse();
        return ans.toString();
    }
}

results of enforcement

adopt
 Execution time: 2 ms,At all Java  Defeated 94 in submission.76%User
 Memory consumption: 38.4 MB,At all Java Defeated 52 in submission.40%User

Complexity analysis

Time complexity: O( max(l1,l2))
Space complexity: O(1) 

πŸ’¬ summary

  • Today is the 75th day of punching out the force deduction algorithm!
  • This paper uses C# and Java programming languages to solve problems
  • Some methods are also written by Likou God, and they are also shared while learning. Thanks again to the algorithm bosses
  • That's the end of today's algorithm sharing. See you tomorrow!

Posted by timmybuck on Thu, 11 Nov 2021 14:11:48 -0800