题目描述:
第一次提交:
class Solution: def addBinary(self, a: str, b: str) -> str: list_a,list_b=[],[] for s in a: list_a.append(int(s)) for s in b: list_b.append(int(s)) if len(list_a)>=len(list_b): for i in range(len(list_a)-len(list_b)): list_b.insert(0,0) else: for i in range(len(list_b)-len(list_a)): list_a.insert(0,0) for i in range(len(list_b)): list_b[i]=list_b[i]+list_a[i] for i in range(len(list_b)-1,0,-1): if list_b[i]>1: list_b[i]=list_b[i]-2 list_b[i-1]+=1 if list_b[0]>1: list_b[0]=list_b[0]-2 list_b.insert(0,1) for i in range(len(list_b)): list_b[i]=str(list_b[i]) strb="".join(list_b) return strb
方法二:使用内置函数
class Solution: def addBinary(self, a: str, b: str) -> str: return bin(int(a,2)+int(b,2))[2:]
其他:
class Solution: def addBinary(self, a: str, b: str) -> str: if len(a) < len(b): a,b = b,a b = "0"*(len(a)-len(b)) + b carry = 0 L = len(a) res = '' while L>0: tmp = int(a[L-1]) + int(b[L-1]) +carry carry = tmp // 2 res += str(tmp % 2) L -= 1 return (res + str(carry))[::-1] if carry else res[::-1]
转换函数:
dec = input('10进制数为:')print("转换为二进制为:", bin(dec))print("转换为八进制为:", oct(dec))print("转换为十六进制为:", hex(dec)) string1 = '101010'print('二进制字符串转换成十进制数为:',int(string1,2))string1 = '367'print('八进制字符串转换成十进制数为:',int(string1,8))string3 = 'FFF'--------------------- 作者:段小胖 来源:CSDN 原文:https://blog.csdn.net/dxcve/article/details/81153331