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; } };
时间: 2024-12-28 05:36:50