2023年5月2日 星期二

5/3 每日一題

 Given two binary strings a and b, return their sum as a binary string.

 

Example 1:

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

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

 

Constraints:

  • 1 <= a.length, b.length <= 104
  • a and b consist only of '0' or '1' characters.
  • Each string does not contain leading zeros except for the zero itself.

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        #先轉成10再轉成2
        #2進制轉10進制
        A=int(a,2) #輸出3,type:int
        B=int(b,2)  #輸出1,type:int
        c=bin(A+B)  #輸出type:str  ,輸出0b100  捨去前兩項(0b)
        return c[2:]

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁