首页 > 代码库 > 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"
.
这个题目只要注意各种情况你就成功了一大半,特别要注意的是对进位赋值后可能产生的变化,以及最后一位进位为1时,
我们要把这个1插进来。同时注意字符串的低位是我们数值的高位
class Solution {public: string addBinary(string a, string b) { reverse(begin(a), end(a)); reverse(begin(b), end(b)); string result; char num = ‘0‘; int i = 0; for (;i < a.size() && i < b.size();++i) { if (a[i] == ‘0‘&&b[i] == ‘0‘&&num == ‘0‘) { result.insert(begin(result), ‘0‘); } if (a[i] == ‘1‘&&b[i] == ‘1‘&&num == ‘1‘) { result.insert(begin(result), ‘1‘); } if ((a[i] == ‘0‘&&b[i] == ‘1‘&&num == ‘1‘) || (a[i] == ‘1‘&&b[i] == ‘0‘&&num == ‘1‘) || (a[i] == ‘1‘&&b[i] == ‘1‘&&num == ‘0‘)) { result.insert(begin(result), ‘0‘); num = ‘1‘; } if (a[i] == ‘1‘&&b[i] == ‘0‘&&num == ‘0‘ || a[i] == ‘0‘&&b[i] == ‘1‘&&num == ‘0‘ || a[i] == ‘0‘&&b[i] == ‘0‘&&num == ‘1‘) { result.insert(begin(result), ‘1‘); num = ‘0‘; } } if (i == a.size()) { for (;i < b.size();++i) { if (b[i] == ‘0‘&&num == ‘0‘) result.insert(begin(result), ‘0‘); if (b[i] == ‘0‘&&num == ‘1‘ || b[i] == ‘1‘&&num == ‘0‘) { result.insert(begin(result), ‘1‘); num = ‘0‘; } if (b[i] == ‘1‘&&num == ‘1‘) result.insert(begin(result), ‘0‘); } } else { for (;i < a.size();++i) { if (a[i] == ‘0‘&&num == ‘0‘) result.insert(begin(result), ‘0‘); if (a[i] == ‘1‘&&num == ‘1‘) result.insert(begin(result), ‘0‘); if (a[i] == ‘0‘&&num == ‘1‘ || a[i] == ‘1‘&&num == ‘0‘) { result.insert(begin(result), ‘1‘); num = ‘0‘; } } } if (num == ‘1‘)result.insert(begin(result), ‘1‘); return result; }};
LeetCode 67. Add Binary
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。