String concatenation

Given two non-negative integer to a string  num1and num2 calculates their sum. (Power button 415 questions)

The question to see the comments area has a sophisticated algorithm.

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;

class Solution 
{
	public:
		string addStrings(string num1, string num2) 
		{
			string str;
			int cur = 0, i = num1.size()-1, j = num2.size()-1;
			while (i> = 0 || j> = 0 || cur! = 0) // will carry value is also set to cycle conditions 
			{
				if (i >= 0) cur += num1[i--] - '0';
				if (j >= 0) cur += num2[j--] - '0';
				str += to_string (cur % 10);
				cur /= 10;
			}
			reverse(str.begin(), str.end());
			return str;
		}
};


int main ()
{
	Solution s;
        string num1("999999999"), num2("1");
	cout<<s.addStrings(num1, num2)<<endl;
	return 0;
}

 operation result

 

 The beauty of this method is that the value and carry value you would put added are added together, and the carry value is also set to the loop condition, so that numbers can be different in the two long, short last character after adding there is a situation carries.

Guess you like

Origin www.cnblogs.com/area-h-p/p/12067519.html