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