大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
Given two binary strings a
and b
, return their sum as a binary string.
Input: a = "11", b = "1"
Output: "100"
Input: a = "1010", b = "1011"
Output: "10101"
1 <= a.length, b.length <= 10^4
a
and b
consist only of '0'
or '1'
characters.首先先簡單的翻譯一下題目
給兩個二進制的數字字串,回傳兩者相加後的值。
作法大致上是這樣
int
並相加,再去判斷相加後的每一位數字有沒有大於2
,有的話就代表要進位,下一個位數的值再判斷有沒有大於2
之前要先加上進位的值。1
,就可以回傳了。class Solution:
def addBinary(self, a: str, b: str) -> str:
flag_add = False
int_a = int(a)
int_b = int(b)
sum = int_a + int_b
sum = list(str(sum))
for index in range(len(sum)-1, -1, -1):
if flag_add:
sum[index] = str(int(sum[index]) + 1)
flag_add = False
if int(sum[index]) >= 2:
sum[index] = str(int(sum[index]) - 2)
flag_add = True
if index == 0:
sum.insert(0, "1")
sum = str(sum).replace("[", "").replace("'", "").replace(",", "").replace("]", "").replace(" ", "")
return sum
Python
大家明天見