https://leetcode-cn.com/problems/add-binary/description/
python下的进制转换
我是按照读字符串的方式先转为10进制,再用bin(x),转回二进制。做完,看了下最快的原来python能直接转。
这是我自己的
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
num1=num2=0
z=0
while(1):
if len(a) == 0:
break
num1=num1+pow(2,z)*int(a[-1])
a=a[:-1]
z+=1
z = 0
while (1):
if len(b) == 0:
break
num2 = num2 + pow(2, z) * int(b[-1])
b = b[:-1]
z += 1
sum = num1+num2
sum = str(bin(sum)[2:])
return sum
这是最快的:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
num=int(a,2)+int(b,2)
ans=bin(num)
return ans[2:]
顺便记录一下python下各类转换
# -*- coding: UTF-8 -*-
# 获取用户输入十进制数
dec = int(input("输入数字:"))
print("十进制数为:", dec)
print("转换为二进制为:", bin(dec))
print("转换为八进制为:", oct(dec))
print("转换为十六进制为:", hex(dec))