首页 > 代码库 > LeetCode——Add Binary

LeetCode——Add Binary

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

For example,
a = "11"
b = "1"

Return "100".

求数字字符串的二进制和。同之前的数组代表数字,两个数组相加一样,只不过进位变成了2.可能两个串的长度不一样,故逆转,从左到右加下去,最后再逆转。

	public static String addBinary(String a, String b) {
		StringBuilder ar = new StringBuilder(a).reverse();
		StringBuilder br = new StringBuilder(b).reverse();
		StringBuilder result = new StringBuilder();
		int len = Math.max(a.length(), b.length());
		int carry = 0;//进位
		for (int i = 0; i < len; i++) {
			int t1 = (i >= a.length() ? 0 : (ar.charAt(i) - '0'));
			int t2 = (i >= b.length() ? 0 : (br.charAt(i) - '0'));
			int t3 = t1 + t2 + carry;
			carry = t3 / 2;
			t3 = t3 % 2;
			result.append(t3);
		}
		if (carry != 0)
			result.append(carry);
		result.reverse();
		return result.toString();
	}