67. Add Binary 二进制转换10进制加法再转换回去

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mygodhome/article/details/84996116

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"
class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        
        x=int("0b"+str(a),2)
        y=int("0b"+str(b),2)
        s=str(bin(x+y)[2:])
        return s
        

 解释x=int("0b"+str(a),2):

二进制转换为十进制有几种方式

第一种是在二进制数前加上0b,显示时会自动转换为十进制,注意这并不是字符串

1

2

= 0b1010

print(x)

如果是字符串可以利用eval求值

1

= eval('0b1010')

第二种是利用int函数,字符串可以以0b为前缀,也可以不使用

1

2

int('1010',base=2)

int('0b1010',2)

函数会将输入base进制的字符串转换为十进制

猜你喜欢

转载自blog.csdn.net/mygodhome/article/details/84996116