leetcode 67. 二进制求和

https://leetcode-cn.com/problems/add-binary/description/
python下的进制转换 python

这是最快的:code

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下各种转换,能够看到直接用format这种转换完了不用二次处理orm

# -*- coding: UTF-8 -*-
printdec =19
print("十进制数为:", dec)
print("转换为二进制为:", bin(dec))
print("转换为八进制为:", oct(dec))
print("转换为十六进制为:", hex(dec))

print("转换为二进制为:", format(dec, 'b'))
print("转换为八进制为:", format(dec, 'o'))
print("转换为十六进制为:", format(dec, 'x'))

 如下是输出,能够看到format后的结果不用二次处理blog

十进制数为: 19
转换为二进制为: 0b10011
转换为八进制为: 0o23
转换为十六进制为: 0x13
转换为二进制为: 10011
转换为八进制为: 23
转换为十六进制为: 13

 将其余进制转回十进制ip

print(int('10011',2))
print(int('23',8))
print(int('13',16))

 

看到个更牛逼的leetcode

format(int(a, 2) + int(b, 2), "b")
相关文章
相关标签/搜索