fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. string addBinary(string a, string b) {
  5. int lenA = a.length(), lenB = b.length();
  6. int i = lenA - 1, j = lenB - 1;
  7. int carry = 0;
  8. stack<char> out;
  9. int sum = 0;
  10. while(i >= 0 || j >= 0){
  11. if(i >= 0 && j >= 0){
  12. sum = a[i] - '0' + b[j] - '0' + carry;
  13. i--;
  14. j--;
  15. }else{
  16. if(i < 0){
  17. sum = b[j] - '0' + carry;
  18. j--;
  19. }
  20. else{
  21. sum = a[i] - '0' + carry;
  22. i--;
  23. }
  24. }
  25. if(sum > 1){
  26. carry = 1;
  27. }else{
  28. carry = 0;
  29. }
  30. sum = sum % 2;
  31. char aChar = '0' + sum;
  32. out.push(aChar);
  33. }
  34. if(carry){
  35. out.push('1');
  36. }
  37. string res = "";
  38. while(!out.empty()){
  39. res = res + out.top();
  40. out.pop();
  41. }
  42. return res;
  43. }
  44.  
  45.  
  46. int main() {
  47. cout << addBinary("11", "1");
  48. return 0;
  49. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
100