1 class Solution { 2 public: 3 string addBinary(string a, string b) { 4 int aL = a.length(); 5 int bL = b.length(); 6 int cL; 7 if (aL > bL) 8 cL = aL + 1; 9 else 10 cL = bL + 1; 11 char *c = new char[cL+1]; 12 int k = aL-1; 13 int j = bL - 1; 14 int flag = 0; 15 for (int i = cL - 1; i >= 1; i--) 16 { 17 if (k == -1) 18 { 19 int sum = b[j] - '0' + flag; 20 c[i] = sum%2+'0'; 21 flag = sum / 2; 22 j--; 23 } 24 else if (j == -1) 25 { 26 int sum = a[k] - '0' + flag; 27 c[i] = sum % 2+'0'; 28 flag = sum / 2; 29 k--; 30 } 31 else 32 { 33 int sum = flag + a[k]-'0' + b[j]-'0'; 34 c[i] = sum % 2 + '0'; 35 flag = sum / 2; 36 k--; 37 j--; 38 } 39 } 40 c[0] = flag + '0'; 41 c[cL] = 0; 42 if (c[0] == '0') 43 return &c[1]; 44 else 45 return c; 46 } 47 };
没什么好讲的,好像也只有把代码写的好看一些,这个以后多加锻炼!