LeetCode Add Binary

来源:互联网 发布:linux中线程退出 编辑:程序博客网 时间:2024/06/01 08:34

新年第一篇

// LeetCode_AddBinary.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>#include <algorithm>#include <string>using namespace std;string addBinary(string a, string b) {int lena = a.length();int lenb = b.length();if (lena==0)return b;if(lenb==0)return a;int i=lena-1,j=lenb-1;bool flag = false;int temp=0;string ret;while(i>=0&&j>=0){temp = a[i]-'0'+b[j]-'0';if(flag)temp++;if(temp>=2){temp -= 2;flag = true;}elseflag = false;ret += (temp+'0');i--;j--;}while(i>=0){temp = a[i] - '0';if(flag)temp++;if (temp>=2){temp -= 2;flag = true;}elseflag = false;ret += (temp+'0');i--;}while(j>=0){temp = b[j] - '0';if(flag)temp++;if (temp>=2){temp -= 2;flag = true;}elseflag = false;ret += (temp+'0');j--;}if(flag)ret += '1';reverse(ret.begin(),ret.end());return ret;}int _tmain(int argc, _TCHAR* argv[]){string a,b;while(cin>>a&&cin>>b)cout<<addBinary(a,b)<<endl;system("pause");return 0;}


0 0
原创粉丝点击