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(); }
时间: 2024-10-13 17:45:55