首页 > 代码库 > 【LeetCode】67. Add Binary 解题小结
【LeetCode】67. 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 res(a.size()+b.size(),‘0‘); int i = a.size()-1; int j = b.size()-1; int k = res.size()-1; int carry = 0; while(i >= 0 || j >= 0 || carry){ int sum = 0; if (i >= 0) sum += a[i--] - ‘0‘; if (j >= 0) sum += b[j--] - ‘0‘; if (carry) sum += carry; res[k--] = ‘0‘ + (sum%2); carry = sum / 2; } std::size_t pos = res.find_first_not_of(‘0‘); return pos == std::string::npos ? "0":res.substr(pos); }};
【LeetCode】67. Add Binary 解题小结
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。