LeetCode-Add Two Binary

Add BinaryApr 2 '12 3558 / 10570

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) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		string ret;
		bool carry=false;
		if(a.size()>b.size())
		{
			int i=a.size()-1,j=b.size()-1;
			while(j>=0){
				int sum=a.c_str()[i]+b.c_str()[j]-2*'0';
				if(carry){
					sum++;
					carry=false;
				}
				if(sum>=2){
					sum-=2;
					carry=true;
				}
				char c=sum+'0';
				ret=c+ret;
				i--;
				j--;
			}
			while(i>=0){
				int sum=a.c_str()[i]-'0';
				if(carry){
					sum++;
					carry=false;
				}
				if(sum>=2){
					sum-=2;
					carry=true;
				}
				char c=sum+'0';
				ret=c+ret;
				i--;
			}
		}
		else
		{
			int i=a.size()-1,j=b.size()-1;
			
			while(i>=0){
				int sum=a.c_str()[i]+b.c_str()[j]-2*'0';
				if(carry){
					sum++;
					carry=false;
				}
				if(sum>=2){
					sum-=2;
					carry=true;
				}
				char c=sum+'0';
				ret=c+ret;
				i--;
				j--;
			}
			while(j>=0){
				int sum=b.c_str()[j]-'0';
				if(carry){
					sum++;
					carry=false;
				}
				if(sum>=2){
					sum-=2;
					carry=true;
				}
				char c=sum+'0';
				ret=c+ret;
				j--;
			}
		}
		if(carry)ret='1'+ret;
		return ret;
	}
};

  

posted @ 2013-07-09 08:54  懒猫欣  阅读(170)  评论(0编辑  收藏  举报