[LeetCode] Add Binary

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

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

从低位到高位模拟二进制相加,如果相加结果产生进位,则对该数对2取余将结果放去结果str中,对该数取商将结果继续循环并与下一对应数位数之和相加。

这里循环条件为a或b未遍历结束和以及产生了进位。

class Solution {
public:
    string addBinary(string a, string b) {
        string str = "";
        int c = 0, i = a.size() - 1, j = b.size() - 1;
        while (i >= 0 || j >= 0 || c == 1) {
            c += i >= 0 ? a[i--] - '0' : 0;
            c += j >= 0 ? b[j--] - '0' : 0;
            str = char(c % 2 +'0') + str;
            c /= 2;
        }
        return str;
    }
};
// 6 ms

 

posted @ 2017-11-03 10:21  immjc  阅读(125)  评论(0编辑  收藏  举报