【leetcode】67-AddBinary

problem

AddBinary

code

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

注意

1.每个字符串中的每个字符对应的数字进行数字运算,且最后的结果是字符串;

2.int型和字符类型之间的转换;

3.string类型可以直接使用符号'+'进行字符串的连接;

4.进位和余数的运算;

 

参考

1.leetcode_AddBinary;

posted on 2018-11-20 16:43  鹅要长大  阅读(137)  评论(0编辑  收藏  举报

导航