Description
https://leetcode.com/problems/add-binary/
二进制字符串表示求和
Solving Ideas
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
Solution
class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int carry = 0;
for (int i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0; i--, j--) {
if (i >= 0) carry += (a.charAt(i) - '0');
if (j >= 0) carry += (b.charAt(j) - '0');
sb.append(carry % 2);
carry /= 2;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
}