Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

思路:学习这种代码的简洁写法。

 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         string res;
 5         int ia = a.size() - 1, ib = b.size() - 1, c = 0;
 6         while (ia >= 0 || ib >= 0 || c == 1)
 7         {
 8             c += (ia >= 0) ? (int)(a[ia--] - '0') : 0;
 9             c += (ib >= 0) ? (int)(b[ib--] - '0') : 0;
10             res = (char)(c % 2 + '0') + res;
11             c = c >> 1;
12         }
13         return res;
14     }
15 };

 

相关文章:

  • 2021-08-03
  • 2021-11-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-01
  • 2021-11-27
  • 2021-06-19
  • 2021-12-11
  • 2021-07-26
  • 2021-12-13
相关资源
相似解决方案