Leetcode:67. Add Binary

Description

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

思路

  • 没啥好说的,注意进位问题。

代码

class Solution {
public:
    string addBinary(string a, string b) {
        int alen = a.size(), blen = b.size();
        if(alen == 0) return b;
        if(blen == 0) return a;
        
        string res;
        int count = 0, sum = 0;
        int i = alen - 1, j = blen - 1;
        while(i >= 0 || j >= 0){
            sum = 0;
            if(i >= 0){
                sum += a[i] - '0';
                i--;
            }
            
            if(j >= 0){
                sum += b[j] - '0';
                j--;
            }
            
            sum += count;
            count = sum / 2;
            sum = sum % 2;
            res += ('0' + sum);
        }
        
        if(count)
            res += '1';
            
        reverse(res.begin(), res.end());
        
        return res;
    }
};
posted @ 2017-05-30 10:45  JeffLai  阅读(96)  评论(0编辑  收藏  举报