同水题,哎,今天无心做难题,只好刷刷水题。
还心不在焉地把i、j打错了,错了好几次,哭,完全没有达到做题的状态!
1 class Solution { 2 public: 3 string addBinary(string a, string b) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int n1 = a.size(); 7 int n2 = b.size(); 8 if (n1 == 0 && n2 == 0) { 9 string res = 0; 10 return res; 11 } 12 if (n1 == 0) { 13 return b; 14 } 15 if (n2 == 0) { 16 return a; 17 } 18 int n = min(n1, n2); 19 int m = max(n1, n2); 20 string s = a; 21 int carry = 0; 22 if (n2 > n1) { 23 s = b; 24 } 25 int i = n1 - 1; 26 int j = n2 - 1; 27 int k = m - 1; 28 while (i >= 0 && j >= 0) { 29 a[i] -= '0'; 30 b[j] -= '0'; 31 s[k] = a[i] + b[j] + carry; 32 if (s[k] >= 2) { 33 s[k] -= 2; 34 s[k] += '0'; 35 carry = 1; 36 } 37 else { 38 carry = 0; 39 s[k] += '0'; 40 } 41 i--; 42 j--; 43 k--; 44 } 45 if (!carry) { 46 return s; 47 } 48 while (k >= 0 && carry) { 49 s[k] -= '0'; 50 s[k] += carry; 51 if(s[k] >= 2) { 52 s[k] -= 2; 53 s[k] += '0'; 54 carry = 1; 55 } 56 else { 57 carry = 0; 58 s[k] += '0'; 59 } 60 k--; 61 } 62 if (!carry) { 63 return s; 64 } 65 string res = "1" + s; 66 return res; 67 } 68 };