力扣:415. 字符串相加

题目部分:

解题思路:

方案一:

方案一演示代码讲解如下:

方案二演示代码讲解如下:

附:方案一、二代码提取:

// 头插方式
class Solution {
          
   
public:
	string addStrings(string num1, string num2) {
          
   
		int end1 = num1.size() - 1, end2 = num2.size() - 1;
		int next = 0; // 进位

		string retStr;
		while (end1 >= 0 || end2 >= 0)
		{
          
   
			int x1 = 0;
			if (end1 >= 0)
			{
          
   
				x1 = num1[end1] - 0;
				--end1;
			}

			int x2 = 0;
			if (end2 >= 0)
			{
          
   
				x2 = num2[end2] - 0;
				--end2;
			}

			int retVal = x1 + x2 + next;
			if (retVal > 9)
			{
          
   
				next = 1;
				retVal -= 10;
			}
			else
			{
          
   
				next = 0;
			}

			// 头插
			retStr.insert(retStr.begin(), retVal + 0);
		}

		if (next == 1)
		{
          
   
			retStr.insert(retStr.begin(), 1);
		}

		return retStr;
	}
};


// 尾插方式
class Solution {
          
   
public:
	string addStrings(string num1, string num2) {
          
   
		int end1 = num1.size() - 1, end2 = num2.size() - 1;
		int next = 0; // 进位

		string retStr;
		while (end1 >= 0 || end2 >= 0)
		{
          
   
			int x1 = 0;
			if (end1 >= 0)
			{
          
   
				x1 = num1[end1] - 0;
				--end1;
			}

			int x2 = 0;
			if (end2 >= 0)
			{
          
   
				x2 = num2[end2] - 0;
				--end2;
			}

			int retVal = x1 + x2 + next;
			if (retVal > 9)
			{
          
   
				next = 1;
				retVal -= 10;
			}
			else
			{
          
   
				next = 0;
			}

			// 头插
			//retStr.insert(retStr.begin(), retVal + 0);
			retStr += retVal + 0;
		}

		if (next == 1)
		{
          
   
			//retStr.insert(retStr.begin(), 1);
			retStr += 1;
		}

		reverse(retStr.begin(), retStr.end());

		return retStr;
	}
};

测试结果:

方案一:

方案二:

不出意外的话家人们肯定是狠狠拿下!

备注:

2023年4月20日

经验分享 程序员 微信小程序 职场和发展