---
# System prepended metadata

title: 67. Add Binary
tags: [Grind 169]

---

# 67. Add Binary

> ***View the book with <i class="fa fa-book"></i> Book Mode.***

- [**LeetCode筆記目錄**](https://hackmd.io/@WeiYee/SyABdj_eA)

## :book: 題目

**網址:**  https://leetcode.com/problems/add-binary/description/

## :dart: 解題步驟
- 相總結果的長度只會等於最長的或最長的 + 1
- 從尾端開始相加，結果覆蓋在最長的字串，另 carry 紀錄進位
                 

## :pencil2: 程式碼
### Java
```java=
class Solution {
    public String addBinary(String a, String b) {
        if (b.length() > a.length()) return addBinaryProcess(b, a);
        else return addBinaryProcess(a, b);
    }

    private String addBinaryProcess(String max, String min) {
        char[] temp = max.toCharArray();
        int indexMax = temp.length - 1, indexMin = min.length() - 1, carry = 0;
        for (; indexMax >= 0 && indexMin >= 0; --indexMax, --indexMin) {
            int num = temp[indexMax] - '0' + min.charAt(indexMin) - '0' + carry;
            carry = num / 2;
            temp[indexMax] = (char) (num % 2 + '0');
        }
        while (indexMax >= 0 && carry == 1) {
            int num = temp[indexMax] - '0' + carry;
            carry = num / 2;
            temp[indexMax--] = (char) (num % 2 + '0');
        }
        return (carry == 1 ? '1' : "") + new String(temp);
    }
}
```

