首页 > 代码库 > Add Binary
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) { string sol; int len1=a.size(); int len2=b.size(); std::reverse(a.begin(),a.end()); std::reverse(b.begin(),b.end()); int i=0; int carry=0; while(i<len1&&i<len2) { int c=(a[i]-‘0‘+b[i]-‘0‘+carry)%2; carry=(a[i]-‘0‘+b[i]-‘0‘+carry)/2; sol.append(1,c+‘0‘); i++; } while(i<len1) { int c=(a[i]-‘0‘+carry)%2; carry=(a[i]-‘0‘+carry)/2; sol.append(1,c+‘0‘); i++; } while(i<len2) { int c=(b[i]-‘0‘+carry)%2; carry=(b[i]-‘0‘+carry)/2; sol.append(1,c+‘0‘); i++; } if(carry!=0)sol.append(1,‘1‘); std::reverse(sol.begin(),sol.end()); return sol; }};
class Solution {public: string addBinary(string a, string b) { string sol; if(b.size()>a.size()) { string t=a; a=b; b=t; } int len1=a.size(); int len2=b.size(); std::reverse(a.begin(),a.end()); std::reverse(b.begin(),b.end()); int i=0; int carry=0; while(i<len2) { int c=(a[i]-‘0‘+b[i]-‘0‘+carry)%2; carry=(a[i]-‘0‘+b[i]-‘0‘+carry)/2; sol.append(1,c+‘0‘); i++; } while(i<len1) { int c=(a[i]-‘0‘+carry)%2; carry=(a[i]-‘0‘+carry)/2; sol.append(1,c+‘0‘); i++; } if(carry!=0)sol.append(1,‘1‘); std::reverse(sol.begin(),sol.end()); return sol; }};
class Solution {public: string addBinary(string a, string b) { string sol; if(b.size()>a.size()) { string t=a; a=b; b=t; } int len1=a.size(); int len2=b.size(); std::reverse(a.begin(),a.end()); std::reverse(b.begin(),b.end()); int i=0; int carry=0; while(i<len2) { int c=(a[i]-‘0‘+b[i]-‘0‘+carry)%2; carry=(a[i]-‘0‘+b[i]-‘0‘+carry)/2; sol.append(1,c+‘0‘); i++; } while(i<len1) { int c=(a[i]-‘0‘+carry)%2; carry=(a[i]-‘0‘+carry)/2; sol.append(1,c+‘0‘); i++; } if(carry!=0)sol.append(1,‘1‘); std::reverse(sol.begin(),sol.end()); return sol; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。