leetcode 67. 二进制求和

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

这是最快的:

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这种转换完了不用二次处理

# -*- 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后的结果不用二次处理

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

 将其他进制转回十进制

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

看到个更牛逼的

format(int(a, 2) + int(b, 2), "b")
原文地址:https://www.cnblogs.com/xiaojinniu425/p/9303722.html