leetcode Add Binary 2.16 难度系数2

Question:

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

For example,
a = "11"
b = "1"
Return "100".

public class Solution {
  public String addBinary(String a, String b) {
		StringBuffer sb = new StringBuffer();

		String s1 = sb.append(a).reverse().toString();
		sb.delete(0, sb.length());
		String s2 = sb.append(b).reverse().toString();
		sb.delete(0, sb.length());
		char[] c1 = s1.toCharArray();
		char[] c2 = s2.toCharArray();
		int c1number = 0;
		int c2number = 0;
		int carry = 0;
		int n = Math.max(c1.length, c2.length);
		for (int i = 0; i < n; i++) {
			if (i < c1.length) {
				c1number = c1[i] - ‘0‘;
			} else {
				c1number = 0;
			}
			if (i < c2.length) {
				c2number = c2[i] - ‘0‘;
			} else {
				c2number = 0;
			}
			int number = c1number + c2number + carry;
			if (number > 1) {
				sb.append(number - 2);
				carry = 1;
			} else {
				sb.append(number);
				carry = 0;
			}

		}
		if (carry == 1) {
			sb.append("1");
		}
		return sb.reverse().toString();
	}
}


leetcode Add Binary 2.16 难度系数2

上一篇:leetcode Unique Paths 2.14 难度系数2


下一篇:JDK环境变量设置