Java for LeetCode 067 Add Binary

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

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

解题思路:

JAVA实现如下:

static public String addBinary(String a, String b) {
		if (a.length() < b.length()) {
			String temp = a;
			a = b;
			b = temp;
		}
		boolean carry = false;
		StringBuilder sb = new StringBuilder(a);
		for (int i = 0; i < b.length(); i++) {
			if (b.charAt(b.length() - 1 - i) == ‘0‘) {
				if (sb.charAt(a.length() - 1 - i) == ‘0‘ && carry) {
					sb.replace(a.length() - 1 - i, a.length() - i, "1");
					carry = false;
				} else if (sb.charAt(a.length() - 1 - i) == ‘1‘ && carry)
					sb.replace(a.length() - 1 - i, a.length() - i, "0");
			} else {
				if (sb.charAt(a.length() - 1 - i) == ‘0‘ && !carry)
					sb.replace(a.length() - 1 - i, a.length() - i, "1");
				else if (sb.charAt(a.length() - 1 - i) == ‘1‘ && !carry) {
					sb.replace(a.length() - 1 - i, a.length() - i, "0");
					carry = true;
				}
			}
		}
		if (!carry)
			return sb.toString();
		for (int i = a.length() - b.length() - 1; i >= 0; i--)
			if (sb.charAt(i) == ‘0‘) {
				sb.replace(i, i + 1, "1");
				return sb.toString();
			} else
				sb.replace(i, i + 1, "0");
		sb.insert(0, ‘1‘);
		return sb.toString();
	}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。