DAY 13
0

## Question

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

## Example

### Example1

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

### Example2

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

### Constraints

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

## 解題

### Think

• 直接將兩個數都轉成`int`並相加，再去判斷相加後的每一位數字有沒有大於`2`，有的話就代表要進位，下一個位數的值再判斷有沒有大於`2`之前要先加上進位的值。
• 最後，如果到第一位數了，還有需要進位的話，就在最前面再補上一個`1`，就可以回傳了。

### Code

#### Python

``````class Solution:
def addBinary(self, a: str, b: str) -> str:
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):
sum[index] = str(int(sum[index]) + 1)

if int(sum[index]) >= 2:
sum[index] = str(int(sum[index]) - 2)
if index == 0:
sum.insert(0, "1")

sum = str(sum).replace("[", "").replace("'", "").replace(",", "").replace("]", "").replace(" ", "")
return sum
``````

#### C

``````
``````

• Python

• ## C

30天 Leetcode解題之路30

### 1 則留言

0
soft_soft
iT邦新手 5 級 ‧ 2021-10-08 20:37:35