Leetcode日练笔记24 #67 #28 Add Binary & Implement strStr()

本文记录了LeetCode中两道题目的解题思路,分别是#67 Add Binary,通过补零、逐位相加并处理进位的方法解决二进制字符串相加问题;以及#28 Implement strStr(),讨论了如何查找字符串的首次出现位置,介绍了Python内置的find()函数来简化问题。
摘要由CSDN通过智能技术生成

#67 Add Binary

Given two binary strings a and b, return their sum as a binary string.

解题思路:

1. 考虑到 string A B 的长度可能不一样所以先补齐零。

2. 然后将string A和B 同一个index的数字求和之后赋予给新的string,new

3. 用for循环去从后往前看new每一个数位是不是大于2。逢二进一。

4.将new转变为string输出。

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        # let string a and b have the same number of digits
        if len(a) > len(b):
            b = '0'*(len(a)-len(b)) + b
        elif len(b) > len(a):
            a = '0'*(len(b)-len(a)) + a
            
        # create a new list to store the sum of int(a) and int(b)
        new = [[] for _ in range(len(a))]
        for i in range(len(a)-1, -1, -1):
            new[i] = int(a[i]) + int(b[i])

        # run through every digits of the list backwards
        # add 1 to the
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值