LeetCode_67. Add Binary

 

67. Add Binary

Easy

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"

 

package leetcode.easy;

public class AddBinary {
	@org.junit.Test
	public void test() {
		String a1 = "11";
		String b1 = "1";
		String a2 = "1010";
		String b2 = "1011";
		System.out.println(addBinary(a1, b1));
		System.out.println(addBinary(a2, b2));
	}

	public String addBinary(String a, String b) {
		StringBuffer buffer = new StringBuffer();
		int sum = 0;
		int carry = 0;
		for (int i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0; i--, j--) {
			sum = carry;
			if (i >= 0) {
				sum += a.charAt(i) - '0';
			}
			if (j >= 0) {
				sum += b.charAt(j) - '0';
			}
			buffer.append(sum % 2);
			carry = sum / 2;
		}
		if (carry != 0) {
			buffer.append(carry);
		}
		return buffer.reverse().toString();
	}
}

 

上一篇:两数相加(二)


下一篇:LeetCode题解002:两数相加