Leetcode 67 Add Binary

来源:互联网 发布:window10 共享端口 编辑:程序博客网 时间:2024/06/02 00:01

Leetcode 67 Add Binary

include <string>using namespace std;class Solution {public:    string addBinary(string a, string b) {    int i = a.length() - 1;    int j = b.length() - 1;    int sum = 0;    string result;    while(i >= 0 || j >= 0)    {        sum += i >= 0 ? (a[i] - '0') : 0;        sum += j >= 0 ? (b[j] - '0') : 0;//sum: 00/01/10/11        result = ((sum & 1) ? "1" : "0") + result;//&1 : the last bit of sum 0/1        sum >>= 1;//right one bit is carry         i --;        j --;    }    return sum ? "1" + result : result;//if sum == 1,need to add the last carry bit    }};