Leetcode 067. 二进制求和 大数加法
地址 https://leetcode-cn.com/problems/add-binary/
给你两个二进制字符串,返回它们的和(用二进制表示)。 输入为 非空 字符串且只包含数字 1 和 0。 示例 1: 输入: a = "11", b = "1" 输出: "100" 示例 2: 输入: a = "1010", b = "1011" 输出: "10101" 提示: 每个字符串仅由字符 '0' 或 '1' 组成。 1 <= a.length, b.length <= 10^4 字符串如果不是 "0" ,就都不含前导零。
解答
字符串的大数加法 不过是二进制
class Solution { public: string addBinary(string a, string b) { char next = '0'; string ans; reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); int al = 0; int bl = 0; while (al < a.size() && bl < b.size()) { int total = (a[al] - '0') + (b[bl] - '0') + (next - '0'); if (total == 3) { ans += "1"; next = '1'; } else if (total == 2) { ans += "0"; next = '1'; } else if (total == 1) { ans += "1"; next = '0'; } else if (total == 0) { ans += "0"; next = '0'; } al++; bl++; } while (al < a.size()) { if (a[al] == '1' && next == '1') { ans += "0"; next = '1'; } else if (a[al] == '0' && next == '0') { ans += "0"; next = '0'; } else { ans += "1"; next = '0'; } al++; } while (bl < b.size()) { if (b[bl] == '1' && next == '1') { ans += "0"; next = '1'; } else if (b[bl] == '0' && next == '0') { ans += "0"; next = '0'; } else { ans += "1"; next = '0'; } bl++; } if (next == '1') { ans += next; } reverse(ans.begin(), ans.end()); return ans; } };
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
![阿里打赏](https://files.cnblogs.com/files/itdef/ali2.bmp)
![微信打赏](https://files.cnblogs.com/files/itdef/weixin2.bmp)