Add Binary (E)
题目
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
题意
实现以字符串表示的二进制加法。
思路
直接从后往前按位相加即可。
代码实现
Java
class Solution {
public String addBinary(String a, String b) {
int i = a.length() - 1, j = b.length() - 1;
int carry = 0;
StringBuilder bits = new StringBuilder();
while (i >= 0 || j >= 0 || carry == 1) {
int sum = carry;
if (i >= 0) {
sum += a.charAt(i--) - '0';
}
if (j >= 0) {
sum += b.charAt(j--) - '0';
}
bits.append(sum % 2);
carry = sum / 2;
}
return bits.reverse().toString();
}
}
JavaScript
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function (a, b) {
let i = 0
let carry = 0
let ans = []
while (i < a.length || i < b.length) {
let sum = carry
sum += i < a.length ? +a[a.length - 1 - i] : 0
sum += i < b.length ? +b[b.length - 1 - i] : 0
carry = Math.trunc(sum / 2)
sum %= 2
ans.unshift(sum)
i++
}
if (carry) {
ans.unshift(carry)
}
return ans.join('')
}