Add Binary(LeetCode)

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.

Example 1:

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

Example 2:

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

给定二进制字符串,实现二进制相加。

思路:一个一个取数,转成整数相加,模是进位,余数是加数。

注意,短的string要补0;最新的余数要加在之前字符串的第一位。

class Solution {
public:
	string addBinary(string a, string b) {
		int m = a.length();
		int n = b.length();
		int carry = 0;
		string res = "";
		int len = max(m, n);
		for (int i = 0; i < len;i++) {
			int p = 0, q = 0;
			if (i < m)
				p = a[m - 1 - i] - '0';
			else
				p = 0; //短的补0

			if (i < n)
				q = b[n - 1 - i] - '0';
			else 
				q = 0;

			
			int tmp = p + q + carry;
			carry = tmp / 2; //进位
			res = to_string( tmp % 2)+res; //余数要加在第一位

		}
		return (carry == 0) ? res : "1" + res;
	}
};





猜你喜欢

转载自blog.csdn.net/u014485485/article/details/80870587