Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

algorithm - Explaining C++ code for adding two strings

I'm trying to solve the following problem, which how to add two strings without converting them to integer. I have found a solution to the problem, but I don't understand it. Would someone explain it in plain english please ?

here is the code :

class Solution {
public:
    string addStrings(string num1, string num2) {
        int i=num1.size()-1,j=num2.size()-1,carry=0;
        string res="";
        while(i>=0||j>=0)
        {
            if(i>=0) carry+=num1[i--]-'0';
            if(j>=0) carry+=num2[j--]-'0';
            res=to_string(carry%10)+res;
            carry/=10;
        }
        return carry?"1"+res:res;
    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Okay! Lemme explain to you. Numbers are from 0-9. So, maximum sum possible is <=18. So, we need to take a flag/count/carry dummy variable which will be 1 when our sum exceeds 10 (num1[i]-'0'+num2[i]-'0'>=10). When we add two numbers we start from the end. Same here we will loop from end to start i.e. while(i>=0 or j>=0 or count). Count is in while statement 'coz what if i=0 &/| j=0 sum is more than 10 then we will need to add an extra one to the start of the string. Add elements from both strings and decrement corresponding counter i--, j--. Add carry either 0 or 1. calculate new carry which will be passed on to the next sum calculation. Take modulo of sum as we want a single digit. Covert it into string and append to res.

My Code

class Solution {
public:
string addStrings(string num1, string num2) {
  int n1 = num1.size(), i = n1 - 1;
  int n2 = num2.size(), j = n2 - 1;
  int carry = 0;
  string res = "";
  while(i>=0 || j>=0 || carry){
      long sum = 0;
      if(i >= 0){sum += (num1[i] - '0');i--;}
      if(j >= 0){sum += (num2[j] - '0');j--;}
      sum += carry; 
      carry = sum / 10;
      sum = sum % 10;
      res = to_string(sum) + res;
  }
  return res;
 }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...