LeetCode Add Binary

链接: https://oj.leetcode.com/problems/add-binary/


大数加法.二进制

class Solution
{
	public:
		string addBinary(string a,string b)
		{
			bool sign=false;
			string ans;
			if(a.length()<b.length())
				swap(a,b);
			for(int i=a.length()-1,j=b.length()-1;i>=0&&j>=0;i--,j--)
			{
				if( a[i]==b[j])
				{
					ans+=sign?'1':'0';
					if(a[i]=='1')
						sign=true;
					if(a[i]=='0')
						sign=false;
				}
				else
				{
					ans+=sign?'0':'1';
						
				}
				
			}
			for(int i=a.length()-b.length()-1;i>=0;i--)
			{
				if(a[i]=='1')
					ans+=sign?'0':'1';
				else
				{
					ans+=sign?'1':'0';
					sign=false;
				}
			}
			if(sign)
			    ans+='1';
			reverse(ans.begin(),ans.end());

			return ans;
		}

};


你可能感兴趣的:(LeetCode)