LeetCode Day54 add-binary

从后向前遍历两个数组,直到最长的遍历完.较短的若已经到头,则置零,求和.最后判断一下是否还有进位,若有,补一位.

class Solution {
public:
    string addBinary(string a, string b) {
        string res="";
        int m=a.size()-1,n=b.size()-1,carry=0;
        while(m>=0||n>=0){
            int p = m >= 0 ? a[m--] - '0' : 0;
            int q = n >= 0 ? b[n--] - '0' : 0;
            int sum=p+q+carry;
            res=to_string(sum%2)+res;
            carry=sum/2;
        }
        return carry==1?"1"+res:res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41394379/article/details/84971146