首页 > 代码库 > Leetcode_Add Binary
Leetcode_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) { size_t na = a.size(); int nb = b.size(); int n = na > nb ? na : nb; string result(n,'0'); int ch= 0; int i= n-1,ia=na-1,ib=nb-1; for(;ia >=0 && ib >= 0; ){ int re = a[ia]-'0'+b[ib]-'0' + ch; ch=re/2; result[i]=re%2+'0'; ia--; ib--; i--; } //int re = a[0]+b[0]-'0'+'0'+ch; while(ia >=0){ int re = a[ia]-'0' +ch; ch = re/2; result[i] = re%2+'0'; ia--; i--; } while(ib >=0){ int re = b[ib]-'0'+ch; ch = re/2; ib--; result[i]= re%2+'0'; i--; } if(ch){ result.insert(0,"1"); } return result; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。