题干:
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1
和 0
。
示例 1:
输入: a = "11", b = "1" 输出: "100"
示例 2:
输入: a = "1010", b = "1011" 输出: "10101"
一开始想的是将二进制数转化为十进制数相加再将相加和转化为二进制数,但这种方法在数字很大的情况下会产生错误,最终还是用了传统的方法一位一位处理,ac代码如下
class Solution { public: string addBinary(string a, string b) { string result = ""; int len1 = a.size(),len2 = b.size(); int temp = 0,c = 0,i = len1 - 1,j = len2 - 1; while(i >= 0 || j >= 0) { temp = c; if(i >= 0) temp += a[i] - '0'; if(j >= 0) temp += b[j] - '0'; c = temp/2; result += to_string(temp % 2); i--,j--; } if(c == 1) result += to_string(c); reverse(result.begin(),result.end()); return result; } };最近刷leetcode真是越来越头痛,哎。。