Take notes - add LeetCode415 strings

Topic Description: given two non negative integers in the form of string, num1 and num2, calculate their sum.

Be careful:

  1. The length of num1 and num2 is less than 5100
  2. num1 and num2 contain only numbers 0-9
  3. num1 and num2 do not contain any leading zeros.

You can't use any built-in BigInteger library, and you can't directly convert the input string to integer form.

At the beginning, I thought of vertical addition. From the last part of the string, I created a result string, added every calculated bit to the result, and carried it to save. When one string is processed and another one is left, but because the details are not handled in place and the iterator is not compatible, I don't know if anyone can see this blog to point out the problem

class Solution {
public:
	int tr(char s)
	{
		return s - '0';
	}
	char dtr(int s)
	{
		return (s + '0');
	}
	string addStrings(string num1, string num2) {
		string res;
		string longer = num1.size() >= num2.size() ? num1 : num2;
		string shorter = num1.size() >= num2.size() ? num2 : num1;
		int j = longer.size() - 1;
		int carry = 0;
		auto it = res.begin();
		for (int i = shorter.size() - 1; i >= 0; i--)
		{
			int sum = tr(longer[j]) + tr(shorter[i]) + carry;
			carry = sum / 10;
			sum = sum % 10;
			res.insert(it, dtr(sum));
			j--;
		}
		if (j == 0 && carry != 0)res.insert(it, dtr(carry));
		if (j != 0)
		{
			if (carry != 0)
			{
				while (j >= 0)
				{
					int sum = tr(longer[j]) + carry;
					carry = sum / 10;
					sum %= 10;
					res.insert(it, dtr(sum));
					j--;
				}
			}
			else
			{
				while (j >= 0)
				{
					res.insert(it, dtr(longer[j]));
					j--;
				}
			}
		}
		return res;
	}
};

I feel that I have no problem in logic, but iterator is incompatible..

Then I read the method of commenting on the big guy. It's very simple and worth learning, so I imitated it

class Solution {
public:
    
    string addStrings(string num1, string num2) {
        string res;
        int carry=0,i=num1.size()-1,j=num2.size()-1;
        while(i>=0||j>=0||carry!=0)
        {
            if(i>=0){carry+=num1[i]-'0';i--;}
            if(j>=0){carry+=num2[j]-'0';j--;}
            int add=carry%10;
            res.insert(res.begin(),char(add+'0'));
            carry/=10;
        }
        return res;
    }
};

This kind of large number can be solved by adding the number stored in string, array and linked list.

Tags: less

Posted on Sun, 10 Nov 2019 13:59:23 -0500 by sujithnair