题目描述
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”
python解法
class Solution:
def addBinary(self, a: str, b: str) -> str:
t = 0
len1 = len(a)
len2 = len(b)
r = []
while len1>0 or len2>0 or t:
x = (int)(a[len1-1])if len1>0 else 0
y = (int)(b[len2-1])if len2>0 else 0
r.append(str((x+y+t)%2))
t = (x+y+t)//2
len1 -= 1
len2 -= 1
r.reverse()
return ''.join(r)
Runtime: 40 ms, faster than 71.25% of Python3 online submissions for Add Binary.
Memory Usage: 13.9 MB, less than 5.41% of Python3 online submissions for Add
题后反思:
- 字符串的join方法要求可迭代对象中的元素为字符串,不能为整数或其他类型
C语言解法
char * addBinary(char * a, char * b){
int len_a = strlen(a), len_b = strlen(b);
int length = len_a > len_b ? len_a+2 : len_b+2;
char *returnBinary = (char*)malloc(sizeof(char)*(length));
returnBinary[length-1] = '\0';
length -= 2;
char c,t = 0;
int i,j;
for(i=len_a-1, j=len_b-1;i>=0 && j>=0;i--,j--)
{
c = (a[i]+b[j]+t-0x60);
returnBinary[length--] = c%(2)+0x30;
t = c/(2);
}
while(i>=0)
{
c = (a[i]+t-0x30);
returnBinary[length--] = c%(2)+0x30;
t = c/(2);
i--;
}
while(j>=0)
{
c = (b[j]+t-0x30);
returnBinary[length--] = c%(2)+0x30;
t = c/(2);
j--;
}
if(t)
{
returnBinary[length--] = '1';
return returnBinary;
}
else
{
return returnBinary+1;
}
}
Runtime: 4 ms, faster than 60.23% of C online submissions for Add Binary.
Memory Usage: 7.1 MB, less than 75.00% of C online submissions for Add Binary.
题后反思:
- 其实可以只使用for循环实现二进制加法,需要用到三目运算符。
文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步