---
# System prepended metadata

title: Leetcode 67. Add Binary
tags: [Leetcode(C++)]

---

# Leetcode 67. Add Binary
###### tags: `Leetcode(C++)`

題目 : https://leetcode.com/problems/add-binary/ 。

想法 : 

    實作加法。

時間複雜度 : O(n)。

程式碼 :

```
class Solution {
public:
    string addBinary(string a, string b) {
        int l1=a.size()-1, l2=b.size()-1, bring=0;
        string ans;
        
        while(l1 >= 0 || l2 >= 0){
            char n1=(l1 >= 0 ? a[l1] : '0'), n2=(l2 >= 0 ? b[l2] : '0');
            
            //cout << a[l1] << " " << b[l2] << " " << bring << endl;
            
            if(n1 == '0' && n2 == '0'){
                if(bring == 1){
                    ans.insert(0,"1"); bring=0;
                }
                else{
                    ans.insert(0,"0");
                }
                
                l1--; l2--;
            }
            if(n1 == '0' && n2 == '1'){
                if(bring == 1){
                    ans.insert(0,"0"); bring=1; 
                }
                else{
                    ans.insert(0,"1");
                }
                
                l1--; l2--;
            }
            if(n1 == '1' && n2 == '0'){
                if(bring == 1){
                    ans.insert(0,"0"); bring=1; 
                }
                else{
                    ans.insert(0,"1");
                }
                
                l1--; l2--;
            }
            if(n1 == '1' && n2 == '1'){
                if(bring == 0){
                    ans.insert(0,"0"); bring=1;
                }
                else{
                    ans.insert(0,"1"); bring=1;
                }
                
                l1--; l2--;
            }
        }
        
        if(bring == 1){
            ans.insert(0,"1");
        }
        
        return ans;
    }
};
```