lintcode-408-二进制求和

408-二进制求和

给定两个二进制字符串,返回他们的和(用二进制表示)。

样例

a = 11
b = 1
返回 100

标签

二进制 字符串处理 脸书

思路

先相加,在处理进位,为了方便操作,将选字符串翻转,使低位位于数组前端

code

class Solution {
public:
    
    /*
     * @param a: a number
     * @param b: a number
     * @return: the result
     */
    string addBinary(string a, string b) {
        // write your code here
        int sizeA = a.size(), sizeB = b.size();
        if (sizeA <= 0 || sizeB <= 0) {
            return string();
        }
        reversalString(a);
        reversalString(b);
        string result;
        int i = 0, carry = 0;
        for (i = 0; i<sizeA && i<sizeB; i++) {
            result += '0' + (a[i] - '0' + b[i] - '0');
        }
        for (; i < sizeA; i++) {
            result += a[i];
        }
        for (; i < sizeB; i++) {
            result += b[i];
        }
        for (i = 0; i < result.size(); i++) {
            int temp = result[i] - '0' + carry;
            if (temp == 2) {
                carry = 1;
                result[i] = '0';
            }
            else if (temp == 3) {
                carry = 1;
                result[i] = '1';
            }
            else {
                carry = 0;
                result[i] = temp + '0';
            }
        }
        if (carry == 1) {
            result += '1';
        }
        reversalString(result);
        return result;
    }
    
    void reversalString(string &str) {
        for (int i = 0; i < str.size() / 2; i++) {
            swap(str[i], str[str.size() - 1 - i]);
        }
    }
};
posted @ 2017-08-14 09:14  LiBaoquan  阅读(793)  评论(0编辑  收藏  举报