[leetcode]Add Binary

Posted on 2013-07-25 18:44  冰天雪域  阅读(142)  评论(0编辑  收藏  举报
class Solution {
public:
    char add(char a, char b, char c, char &carry){
        int result = a - '0' + b -'0' + c-'0';
        if(result == 0){
            carry = '0';
            return '0';
        }else if(result == 1){
            carry = '0';
            return '1';
        }else if(result == 2){
            carry = '1';
            return '0';
        }else{
            carry = '1';
            return '1';
        }
        
    }

    string addBinary(string a, string b) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(a.empty() || b.empty()) return "";
        
        if(b.size() > a.size()) swap(a,b);
        
        int p = a.size()-1;
        int q = b.size()-1;
        
        string c = a;
        char carry = '0';
        char nc;
        
        while(q >= 0){
            c[p] = add(a[p], b[q], carry, nc);
            carry = nc;
            p--;
            q--;  
        }
        
        while(p >= 0){
            c[p] = add(a[p], '0', carry, nc);
            carry = nc;
            p--;
        }
        
        if(carry == '1'){
            c.insert(c.begin(), '1');
        }
        return c;    
        
    }
};


Copyright © 2024 冰天雪域
Powered by .NET 8.0 on Kubernetes