---
# System prepended metadata

title: 0067. Add Binary
tags: [Leetcode, Add Simulation, FaceBook, Easy]

---

# 0067. Add Binary
###### tags: `Leetcode` `FaceBook` `Easy` `Add Simulation`
Link: https://leetcode.com/problems/add-binary/
## 思路
add两个数的题都是这样写
都用StringBuilder，因为最后可能要append carry
## Code
```java=
class Solution {
    public String addBinary(String a, String b) {
        StringBuffer res = new StringBuffer();
        int add = 0;
        int n1, n2;
        for(int i = 0;i < Math.max(a.length(),b.length());i++){
            n1 = i<a.length()?a.charAt(a.length()-1-i)-'0':0;
            n2 = i<b.length()?b.charAt(b.length()-1-i)-'0':0;
            res.append((add+n1+n2)%2==1?'1':'0');
            add = (add+n1+n2)/2;
        }
        if(add == 1) res.append('1');
        return res.reverse().toString();
    }
}
```