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