Big Integer Addition

/*
问题描述:Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2
来源:LintCode
作者:syt

日期:2017-7-16

思路:写了两个方法,但大致差不多,基本思路就是取出字符串中的数相加,需要注意低位进位和最高位的进位,感觉应该有更加简单的方法,继续思考

*/

#include <iostream>
#include <string>
using namespace std;

class AddStrings{
public:
	/**
	* @param num1 a non-negative integers
	* @param num2 a non-negative integers
	* @return return sum of num1 and num2
	*/
	//方法1
	string addStrings1(string& num1, string& num2) {
		// Write your code here

		if (num1.length() < num2.length())
		{
			string tmp = num1;
			num1 = num2;
			num2 = tmp;
		}
	
		int len1 = num1.length() - 1;
		int len2 = num2.length() - 1;


		string result = "";
		bool is = false; //处理进位
		while (len1 >= 0 && len2 >= 0)
		{
			int tmp1 = num1[len1] - 48;
			int tmp2 = num2[len2] - 48;
			int tmp = tmp1 + tmp2;
			if (is)
				tmp++;
			if (tmp >= 10)
			{
				is = true;
				tmp = tmp - 10;
			}
			else
				is = false;

			result = to_string(tmp) + result;
			len1--;
			len2--;
		}

		while (len1 >= 0)
		{
			int tmp = num1[len1] - 48;
			if (is)
				tmp++;
			if (tmp >= 10)
			{
				is = true;
				tmp = tmp - 10;
			}
			else
				is = false;
			result = to_string(tmp) + result;
			len1--;
		}
		if (is)
			result = "1" + result;

		return result;
	}

	//方法2
	string addStrings(string& num1, string& num2) {
		// Write your code here
		if (num1.length() < num2.length())
		{
			string tmp = num1;
			num1 = num2;
			num2 = tmp;
		}
		int len2 = num2.length() - 1;
		int len = num1.length() - 1;
		bool is = false;
		while (len2 >= 0)
		{
			int tmp = num1[len] + num2[len2] - 96;
			if (is)
				tmp++;
			if (tmp >= 10)
			{
				is = true;
				tmp = tmp - 10;
			}
			else
				is = false;
			//cout << tmp << endl;
			num1[len] = tmp + 48;
			len--;
			len2--;
		}

		while (len >= 0)
		{
			int tmp = num1[len] - 48;
			if (is)
				tmp++;
			if (tmp >= 10)
			{
				is = true;
				tmp = tmp - 10;
			}
			else
				is = false;
			num1[len] = tmp + 48;
		
			len--;
		}
		if (is)
			num1 = "1" + num1;
		return num1;
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值