---
# System prepended metadata

title: 67. Add Binary
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
::-webkit-scrollbar {
    width: 10px;
}
::-webkit-scrollbar-track {
    background: transparent;
}
::-webkit-scrollbar-thumb {
    background: linear-gradient(180deg, #2BE8CF60 0%, #2B83E860 100%);
    border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(180deg, #2BE8CF95 0%, #2B83E895 100%);
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}
   
</style>

###### tags: `Leetcode`

# 67. Add Binary


###### Link : https://leetcode.com/problems/add-binary/description/

## 題目
二進制加總
## 程式碼 

```cpp=
class Solution {
public:
    string addBinary(string a, string b) {
        string ans;
        while(a.size() < b.size()) a = "0" + a;
        while(a.size() > b.size()) b = "0" + b;
        bool carryout = false;
        for(int i = a.size() - 1;i >= 0;--i){
            if(a[i] == b[i]){
                if(carryout) ans = "1" + ans;
                else ans = "0" + ans;
                if(a[i] == '1') carryout = true;
                else carryout = false;
            }
            else{
                if(carryout) ans = "0" + ans;
                else ans = "1" + ans;
            }
        }
        if(carryout) ans = "1" + ans;
        return ans;
    }
};
```