leetcood学习笔记-67-二进制求和
2024-09-06 10:23:43
题目描述:
第一次提交:
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 = ""*(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 = ''
print('二进制字符串转换成十进制数为:',int(string1,2))
string1 = ''
print('八进制字符串转换成十进制数为:',int(string1,8))
string3 = 'FFF' ---------------------
作者:段小胖
来源:CSDN
原文:https://blog.csdn.net/dxcve/article/details/81153331
最新文章
- webControls与客户端脚本路径
- Invoke--转载
- Android Fragment (二) 实例2
- ie11浏览器和chrome浏览器对于bgsound和background的一些区别
- Linux企业集群用商用硬件和免费软件构建高可用集群PDF
- gridpanel分组汇总
- PANIC : Error configuring AvalonLogSystem :
- T-SQL:SQL Server-数据开发(经典)
- VSTO之旅系列(一):VSTO入门
- 12.1、Libgdx的图像之持续性和非持续性渲染
- 洛谷P1066 2^k进制数(题解)(递推版)
- mysql自增长主键,删除数据后,将主键顺序重新排序
- C# Winform开发程序调用VLC播放器控件播放视频.
- 缓存系列之二:CDN与其他层面缓存
- 最优贸易 [NOIP 2009]
- macos下golang 1.9配置
- IIS 负载均衡
- go 包-锁机制
- Angular 快速学习笔记(1) -- 官方示例要点
- TestNg的IReporter接口的使用