67. Add Binary
题目描述和难度
- 题目描述:
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1
和 0
。
示例 1:
输入: a = "11", b = "1" 输出: "100"
示例 2:
输入: a = "1010", b = "1011" 输出: "10101"
- 题目难度:简单。
- 英文网址:67. Add Binary 。
- 中文网址:67. 二进制求和 。
思路分析
求解关键:
参考解答
参考解答1
Python 写法:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
res = ''
# 分别表示两个数从后向前的索引,后对齐
i = len(a) - 1
j = len(b) - 1
# 表示进位标志
carry = 0
while i >= 0 or j >= 0:
s = carry
if i >= 0:
s += ord(a[i]) - ord('0')
i -= 1
if j >= 0:
s += ord(b[j]) - ord('0')
j -= 1
res = str(s % 2) + res
carry = s // 2
if carry == 1:
return '1' + res
return res
参考解答2
Java 写法:
public class Solution {
public String addBinary(String a, String b) {
int aLen = a.length();
int bLen = b.length();
int maxLen = Math.max(aLen, bLen);
StringBuilder sa = new StringBuilder(a).reverse();
StringBuilder sb = new StringBuilder(b).reverse();
while (sa.length() < maxLen) {
sa.append("0");
}
while (sb.length() < maxLen) {
sb.append("0");
}
StringBuilder res = new StringBuilder();
int sum = 0;
int num1;
int num2;
for (int i = 0; i < maxLen; i++) {
num1 = sa.charAt(i) - '0';
num2 = sb.charAt(i) - '0';
if (sum + num1 + num2 > 1) {
res.append(sum + num1 + num2 - 2);
sum = 1;
} else {
res.append(sum + num1 + num2);
sum = 0;
}
}
if (sum == 1) {
res.append("1");
}
return res.reverse().toString();
}
public static void main(String[] args) {
String a = "1010";
String b = "1011";
Solution solution = new Solution();
String addBinary = solution.addBinary(a, b);
System.out.println(addBinary);
}
}
Python 写法:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
alen = len(a)
blen = len(b)
maxlen = max(alen, blen)
ra = list(reversed(a))
rb = list(reversed(b))
while len(ra) < maxlen:
ra.append('0')
while len(rb) < maxlen:
rb.append('0')
result = []
s = 0
zero = ord('0')
for i in range(maxlen):
num1 = ord(ra[i]) - zero
num2 = ord(rb[i]) - zero
if s + num1 + num2 > 1:
result.append(str(s + num1 + num2 - 2))
s = 1
else:
result.append(str(s + num1 + num2))
s = 0
if s == 1:
result.append(str(1))
return ''.join(list(reversed(result)))
if __name__ == '__main__':
a = "11"
b = "1"
solution = Solution()
result = solution.addBinary(a, b)
print(result)
参考解答2
Python 写法:
class Solution:
def addBinary(self, a, b):
return bin(int(a, 2) + int(b, 2))[2:]
if __name__ == '__main__':
a = "11"
b = "1"
solution = Solution()
result = solution.addBinary(a, b)
print(result)
result1 = int(a, 2)
result2 = int(b, 2)
print(result1)
print(result2)
print(bin(result1 + result2))
print(bin(result1 + result2)[2:])
本篇文章的地址为 https://liweiwei1419.github.io/leetcode-solution/leetcode-0067-add-binary ,如果我的题解有错误,或者您有更好的解法,欢迎您告诉我 liweiwei1419@gmail.com 。