自己写的
class Solution: def addBinary(self, a: str, b: str) -> str: a_len=len(a) b_len=len(b) if a_len<b_len: temp=b b=a a=temp a_len = len(a) b_len = len(b) b_list=list() com_len=min(a_len,b_len) res_list = [0]*com_len res_fro_list=[0]*(a_len-com_len) a_fro = a[0:a_len-com_len] a_back = a[a_len-com_len:a_len] a_fro_list=list() a_fro_len = len(a_fro) a_back_list=list() a_back_len=len(a_back) for i in range(a_fro_len): a_fro_list.append(int(a_fro[i])) for i in range(a_back_len): a_back_list.append(int(a_back[i])) for i in range(b_len): b_list.append(int(b[i])) carry=0 for i in range(com_len-1,-1,-1): res_list[i]=a_back_list[i]+b_list[i]+carry carry=res_list[i]//2 res_list[i]=res_list[i]%2 for i in range(a_len-com_len-1,-1,-1): res_fro_list[i]=a_fro_list[i]+carry carry=res_fro_list[i]//2 res_fro_list[i]=res_fro_list[i]%2 final_list=res_fro_list+res_list if carry: final_list.insert(0,carry) final_str=str() for i in range(len(final_list)): final_str+=str(final_list[i]) return final_str a = "1" b = "111" sol=Solution().addBinary(a,b) print(sol)
gpt写的
class Solution: def addBinary(self, a: str, b: str) -> str: a_len, b_len = len(a), len(b) # 使得 a 的长度不小于 b,可以避免后续的交换操作 if a_len < b_len: a, b = b, a a_len, b_len = b_len, a_len res_list = [] carry = 0 # 从右向左遍历两个字符串 for i in range(1, a_len + 1): bit_a = int(a[-i]) bit_b = int(b[-i]) if i <= b_len else 0 # 计算当前位的和 current_sum = bit_a + bit_b + carry # 更新进位和当前位的值 carry = current_sum // 2 digit = current_sum % 2 res_list.insert(0, str(digit)) # 如果最终还有进位,插入到列表的开头 if carry: res_list.insert(0, str(carry)) return ''.join(res_list)
标签:addBinary,二进制,self,leedcode,len,求和,int,str From: https://www.cnblogs.com/yyyjw/p/17984660