【LeetCode】42. Add Binary

题目描述(Medium)

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

题目链接

https://leetcode.com/problems/add-binary/description/

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

算法分析

提交代码:

class Solution {
public:
	string addBinary(string a, string b) {
		string result;
		int i = a.length() - 1, j = b.length() - 1;
		int val = 0;

		while (i >= 0 || j >= 0 || val == 1)
		{
			val += i >= 0 ? a[i--] - '0' : 0;
			val += j >= 0 ? b[j--] - '0' : 0;
			result.insert(result.begin(), val % 2 + '0');
			val /= 2;
		}

		return result;
	}
};

测试代码:

// ====================测试代码====================
void Test(const char* testName, string a, string b, string expected)
{
	if (testName != nullptr)
		printf("%s begins: \n", testName);

	Solution s;
	string result = s.addBinary(a, b);

	if(result == expected)
		printf("passed\n");
	else
		printf("failed\n");
}

int main(int argc, char* argv[])
{
	
	Test("Test1", string("11"), string("1"), string("100"));
	Test("Test2", string("1010"), string("1011"), string("10101"));

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82348429