一刷 07/2022
Version #1 Iteration
Time O(N)
Space O(1)
Runtime: 2 ms, faster than 90.84% of Java online submissions for Add Binary.
Memory Usage: 43 MB, less than 45.39% of Java online submissions for Add Binary.
class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int carry = 0;
int i = a.length() - 1;
int j = b.length() - 1;
while (i >= 0 || j >= 0 || carry > 0) {
int bitA = i >= 0 ? a.charAt(i) - '0' : 0;
int bitB = j >= 0 ? b.charAt(j) - '0' : 0;
int sum = bitA + bitB + carry;
// 3 - 1 1
//
carry = sum / 2;
sb.append((char)(sum % 2 + '0'));
i--;
j--;
}
return sb.reverse().toString();
}
}
No comments:
Post a Comment