Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
字符串相加,不难
个人思路:
1,尾部对齐,然后逐位相加,flag记为进位
代码:
1 #include <string> 2 3 using namespace std; 4 5 class Solution { 6 public: 7 string addBinary(string a, string b) { 8 if (a.empty()) 9 { 10 return b; 11 } 12 if (b.empty()) 13 { 14 return a; 15 } 16 17 int aLen = a.length(); 18 int bLen = b.length(); 19 int i = aLen - 1, j = bLen - 1; 20 int flag = 0; //进位 21 int temp, ai, bj; 22 string result; 23 24 for (; i >= 0 || j >= 0; --i, --j) 25 { 26 ai = i >= 0 ? (a[i] - '0') : 0; 27 bj = j >= 0 ? (b[j] - '0') : 0; 28 29 temp = ai + bj + flag; 30 flag = temp > 1 ? 1 : 0; 31 temp = temp - flag * 2; 32 33 result.insert(result.begin(), temp + '0'); 34 } 35 36 if (flag) 37 { 38 result.insert(result.begin(), '1'); 39 } 40 41 return result; 42 } 43 };