---
# System prepended metadata

title: 67. Add Binary
tags: [math, leetcode, string]

---

# 67. Add Binary

題目：<https://leetcode.com/problems/add-binary/>

解法一：將 binary string 轉成 integer，相加後再轉成 binary string，但需要注意數值上限，因此C語言不能這樣做。

Python3：

``` python 3
class Solution:
    def addBinary(self, a: str, b: str) -> str:
        return f'{int(a, 2) + int(b, 2):b}'

if __name__ == '__main__':
    a = "1010"
    b = "1011"

    ans = Solution().addBinary(a, b)
    print(ans)
```

解法二：大數加法運算，依照位數順序相加並處理進位，將結果存入新的陣列中，由於可能因為進位而增加長度，故儲存結果的陣列會先宣告可能的最大長度，並以0當個位數往後儲存，輸出時才會將陣列反轉。

C：

``` c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * addBinary(char * a, char * b) {
    char * c = (char*)malloc(sizeof(char) * 10002);
    int lena = strlen(a) - 1;
    int lenb = strlen(b) - 1;
    int lenc = 0;
    int carry = 0;
    while (lena >= 0 || lenb >= 0 || carry > 0) {
        int tmp = carry;
        if (lena >= 0)
            tmp += a[lena--] - '0';
        if (lenb >= 0)
            tmp += b[lenb--] - '0';
        carry = tmp / 2;
        tmp %= 2;
        c[lenc++] = '0' + tmp;
    }
    c[lenc] = '\0';
    for (int i = 0; i < lenc / 2; i++) {
        char tmp = c[i];
        c[i] = c[lenc - 1 - i];
        c[lenc - 1 - i] = tmp;
    }
    return c;
}

int main() {
    char a[] = "1010";
    char b[] = "1011";
    
    char *ans = addBinary(a, b);
    printf("%s\n", ans);
    return 0;
}
```

###### tags: `leetcode` `math` `string`
