Add and Carry
1 | class Solution { |
Remarks:
- TC: $O(n^2)$ (
sb.insert()
moves all chars each time), SC: $O(n)$. - if-else statements might be combined and simplified to:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25class Solution {
public String addBinary(String a, String b) {
int n = a.length();
int m = b.length();
StringBuilder sb = new StringBuilder();
int max = Math.max(n, m);
int carry = 0;
for (int i = 0; i < max; i++) {
int curA = (n - i - 1 >= 0) ? a.charAt(n - i - 1) - '0' : 0;
int curB = (m - i - 1 >= 0) ? b.charAt(m - i - 1) - '0' : 0;
int sum = curA + curB + carry;
sb.insert(0, sum % 2);
carry = sum / 2;
}
if (carry == 1) {
sb.insert(0, "1");
}
return sb.toString();
}
} - If replace
sb.insert(0, ...)
bysb.append(...)
+sb.reverse()
, we can save more time, as below.
StringBuilder append
+ reverse
1 | class Solution { |
Remarks:
- TC: $O(n)$, SC: $O(n)$.