[LeetCode]67. Add Binary ★

题目描述

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
题后反思:

  1. 字符串的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.
题后反思:

  1. 其实可以只使用for循环实现二进制加法,需要用到三目运算符。
    文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值