Add Binary

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

For example,
a = “11”
b = “1”
Return “100”.

题目翻译: 对于给定的两个二进制数字所表达的字符串,我们求其相加所得到的结果, 根据上例便可得到答案.

题目分析: 我认为这道题所要注意的地方涵盖以下几个方面:

  1. 对字符串的操作.
  2. 对于加法,我们应该建立一个进位单位,保存进位数值.
  3. 我们还要考虑两个字符串如果不同长度会怎样.
  4. int 类型和char类型的相互转换.

时间复杂度:其实这就是针对两个字符串加起来跑一遍,O(n) n代表长的那串字符串长度.

代码如下:

  1. class Solution {
  2. public:
  3. string addBinary(string a, string b) {
  4. int len1 = a.size();
  5. int len2 = b.size();
  6. if(len1 == 0)
  7. return b;
  8. if(len2 == 0)
  9. return a;
  10. string ret;
  11. int carry = 0;
  12. int index1 = len1-1;
  13. int index2 = len2-1;
  14. while(index1 >=0 && index2 >= 0)
  15. {
  16. int num = (a[index1]-'0')+(b[index2]-'0')+carry;
  17. carry = num/2;
  18. num = num%2;
  19. index1--;
  20. index2--;
  21. ret.insert(ret.begin(),num+'0');
  22. }
  23. if(index1 < 0&& index2 < 0)
  24. {
  25. if(carry == 1)
  26. {
  27. ret.insert(ret.begin(),carry+'0');
  28. return ret;
  29. }
  30. }
  31. while(index1 >= 0)
  32. {
  33. int num = (a[index1]-'0')+carry;
  34. carry = num/2;
  35. num = num%2;
  36. index1--;
  37. ret.insert(ret.begin(),num+'0');
  38. }
  39. while(index2 >= 0)
  40. {
  41. int num = (b[index2]-'0')+carry;
  42. carry = num/2;
  43. num = num%2;
  44. index2--;
  45. ret.insert(ret.begin(),num+'0');
  46. }
  47. if(carry == 1)
  48. ret.insert(ret.begin(),carry+'0');
  49. return ret;
  50. }
  51. };