力扣算法题—067二进制求和
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1
和 0
。
示例 1:
输入: a = "11", b = "1" 输出: "100"
示例 2:
输入: a = "1010", b = "1011" 输出: "10101"
1 #include "_000库函数.h" 2 3 //从末尾一位一位的相加 4 class Solution { 5 public: 6 string addBinary(string a, string b) { 7 if (a.empty())return b; 8 if (b.empty())return a; 9 int p1 = a.size() - 1,p2=b.size()-1; 10 string res = p1 > p2 ? a : b;//选用较长的二进制做基 11 int p = p1 > p2 ? p1 : p2; 12 int s = 0;//进位 13 while (p>=0) { 14 if (min(p1, p2) >= 0)//两数相加 15 s = a[p1--] - '0' + b[p2--] - '0' + s; 16 else 17 s = res[p] - '0' + s;//进位想加 18 19 res[p--] = s % 2 + '0'; 20 s = s / 2; 21 } 22 if (s) {//进位 23 a = "1"; 24 res = a + res; 25 } 26 return res; 27 } 28 }; 29 30 //下面这种写法又巧妙又简洁,用了两个指针分别指向a和b的末尾, 31 //然后每次取出一个字符,转为数字,若无法取出字符则按0处理, 32 //然后定义进位carry,初始化为0,将三者加起来,对2取余即为当前位的数字, 33 //对2取商即为当前进位的值,记得最后还要判断下carry,如果为1的话,要 34 //在结果最前面加上一个1,参见代码如下: 35 class Solution { 36 public: 37 string addBinary(string a, string b) { 38 string res = ""; 39 int m = a.size() - 1, n = b.size() - 1, carry = 0; 40 while (m >= 0 || n >= 0) { 41 int p = m >= 0 ? a[m--] - '0' : 0; 42 int q = n >= 0 ? b[n--] - '0' : 0; 43 int sum = p + q + carry; 44 res = to_string(sum % 2) + res; 45 carry = sum / 2; 46 } 47 return carry == 1 ? "1" + res : res; 48 } 49 }; 50 void T067() { 51 Solution s; 52 string a, b; 53 a = "11"; 54 b = "1"; 55 cout << s.addBinary(a, b) << endl; 56 a = "1010"; 57 b = "1011"; 58 cout << s.addBinary(a, b) << endl; 59 a = "11010"; 60 b = ""; 61 cout << s.addBinary(a, b) << endl; 62 63 64 }