Loading

[LeetCode]二进制求和

题目

 

代码

class Solution {
public:
	string addBinary(string a, string b)
	{
		int lenA = a.length();
		int lenB = b.length();
		string result;
		int addFlag = 0;
		int i;
		int current = 0;
		for (i = 0;i < lenA&&i < lenB;i++)
		{
			int numA = a[lenA - i - 1] - '0', numB = b[lenB - i - 1] - '0';
			current = (addFlag + numA + numB) % 2;
			result.push_back((char)('0' + current));
			addFlag = numA + numB + addFlag > 1 ? 1 : 0;


		}

		if (lenA > lenB)
		{
			for (;i < lenA;i++)
			{
				current = ((a[lenA - i - 1] - '0') + addFlag) % 2;
				result.push_back('0' + current);
				addFlag = a[lenA - i - 1]-'0' + addFlag > 1 ? 1 : 0;
			}
			if (addFlag == 1)
				result.push_back('1');
		}
		else if (lenA < lenB)
		{
			for (;i < lenB;i++)
			{
				current = ((b[lenB - i - 1] - '0') + addFlag) % 2;
				result.push_back('0' + current);
				addFlag = b[lenB - i - 1]-'0' + addFlag > 1 ? 1 : 0;
			}
			if (addFlag == 1)
				result.push_back('1');
		}
		else
		{
			if (addFlag == 1)
				result.push_back('1');
		}
		std::reverse(result.begin(), result.end());
		return result;
	}
};

 

posted @ 2019-02-22 12:26  李正浩  阅读(139)  评论(0编辑  收藏  举报