leetcode#415. String addition

Topic link

Title description:

Given two non-negative integers num1 and num2 in the form of strings, calculate their sum.

note:

The length of
num1 and num2 are both less than 5100. Both num1 and num2 only contain the numbers 0-9.
Neither num1 nor num2 contain any leading zeros.
You cannot use any built-in BigInteger library, nor can you directly convert the input string into an integer form.

Problem-solving ideas

  From num1and num2at the end of traversing, bit by bit added. There are four main aspects to consider:

  1. Carry calculation: carry = temp / 10represents the result of the carry after the current bit is added
  2. Calculate the current temp = (n1 + n2 + carry) % 10position: . Then add the result to the resulttail
  3. forThe judgment condition in the loop is added carry != 0to judge whether the addition of the highest bit overflows
  4. If i, jhave run head, for example 131 + 92, then to the corresponding n1or n2set0

  When the loop is completed, resultthe order we found is reversed, and we need reverseto output it later.


Code

class Solution {
    
    
public:
    string addStrings(string num1, string num2) {
    
    
        string result = "";
        int carry = 0;       
        for(int i = num1.size() - 1, j = num2.size() - 1; 
            i >= 0 || j >= 0 || carry != 0;
            i--, j--){
    
    
            
            int n1 = i < 0 ? 0 : num1[i] - '0';
            int n2 = j < 0 ? 0 : num2[j] - '0';
            int temp = (n1 + n2 + carry) % 10;
            result += to_string(temp);
            carry = (n1 + n2 + carry) / 10;

        }
        reverse(result.begin(), result.end());
        return result;
    }
};

If there are mistakes or not rigorous, please correct me, thank you very much.
My blog: http://breadhunter.gitee.io

Guess you like

Origin blog.csdn.net/weixin_40807714/article/details/104965018