【LeetCode】67. Add Binary

问题描述

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

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

二进制加法

代码

class Solution {
public:
    string addBinary(string a, string b) {
        int cur=0;
        int max = a.length()>b.length()?a.length():b.length();
        string r(max, '0');
        for(int i=0, p=a.length()-1, q=b.length()-1;i<max;i++,q--,p--) {
        	if(p<0&&q>=0) {
        		int tmp = ((b[q]-'0')+cur)%2;
				r[max-1-i] = tmp + '0';
				cur = b[q]=='1'&&cur==1?1:0;
	        } else if(p>=0&&q<0) {
	        	int tmp = ((a[p]-'0')+cur)%2;
        		r[max-1-i] = tmp + '0';
				cur = a[p]=='1'&&cur==1?1:0;
        	} else {
				int tmp = (a[p]+b[q]-2*'0'+cur)%2;
				r[max-1-i] = tmp + '0';
				cur = (a[p]+b[q]-2*'0'+cur>=2)?1:0;
	        }
        }
        if(cur==1){
        	string t(1,cur+'0');
        	r = t+r;
        }
        return r;
    }
};