---
# System prepended metadata

title: Leetcode 67. Add Binary
tags: [Leetcode, 字元用法]

---

# Leetcode 67. Add Binary
###### tags: `Leetcode` `字元用法`

題目 
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"

解法:
1.先用strlen得到兩個字串的長度
2.把長度加二就是要回傳字串的長度（一個是給可能的進位，一個是給結尾'\0'）
3.接下來就比較tricky，讀出a、b同位置的值加進carry裡面，只要看carry二進位的最後一個是0還是1就可以決定當下位置的值，而多出來的carry就右移一位當作下個的carry來用（參考程式碼比較好懂）
4.記得若要把字串轉成數字可用a[index]-'0'就可以得到數字字元轉成數字了(ASCII code)

＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝

```
char * addBinary(char * a, char * b){
    int aLen = strlen(a);
    int bLen = strlen(b);
    int resLen = 0;
    int carry = 0;
    if(aLen < bLen)
        resLen = bLen;
    else
        resLen = aLen;
    char* res = malloc(sizeof(char)*(resLen+2));
    res[resLen+1] = '\0';
    
    while(aLen || bLen)
    {
        if(aLen)
            carry += a[--aLen] - '0';
        if(bLen)
            carry += b[--bLen] - '0';
        res[resLen--] = (carry&1) + '0';
        carry>>=1;
    }
    res[0] = 1+'0';
    printf("%p\n%p\n", res, res+1);
    return res+(carry^1);
    // return res+1 => first bit is 0
    // return res   => first bit is 1
}
```