fork download
  1. #include<iostream>
  2. using namespace std;
  3.  
  4.  
  5. string add(string a, string b)
  6. {
  7. int al=a.size()-1;
  8. int bl=b.size()-1;
  9.  
  10. int carry=0;
  11. string result="";
  12.  
  13. while(al>=0 && bl>=0)
  14. {
  15. int temp = (int)(a[al] - '0') + (int)(b[bl] - '0') + carry ;
  16. carry = 0;
  17. if(temp > 9 )
  18. {
  19. carry=1;
  20. temp=temp-10;
  21. }
  22.  
  23. result+=char(temp + '0');
  24. al--;
  25. bl--;
  26. }
  27.  
  28. while(al>=0)
  29. {
  30. int temp = (int)(a[al] - '0') + carry ;
  31. carry = 0;
  32. if(temp>9)
  33. {
  34. carry=1;
  35. temp=temp%10;
  36. }
  37.  
  38. result+=char(temp + '0');
  39. al--;
  40. }
  41.  
  42. while(bl>=0)
  43. {
  44. int temp = (int)(b[bl] - '0') + carry ;
  45. carry = 0;
  46. if(temp>9)
  47. {
  48. carry=1;
  49. temp=temp%10;
  50. }
  51.  
  52. result+=char(temp + '0');
  53. bl--;
  54. }
  55.  
  56. if(carry)
  57. result+="1";
  58.  
  59. string addition="";
  60.  
  61. for(int i=result.size()-1;i>=0;i--)
  62. addition+=result[i]; // reversing the answer
  63.  
  64. return addition;
  65. }
  66.  
  67. string trim(string a) // for removing leading 0s
  68. {
  69. string res="";
  70. int i=0;
  71.  
  72. while(a[i]=='0')
  73. i++;
  74.  
  75. for(;i<a.size();i++)
  76. res+=a[i];
  77.  
  78. return res;
  79. }
  80.  
  81.  
  82. int main()
  83. {
  84. string a = "999999999999";
  85. string b = "1";
  86.  
  87. cin>>a>>b;
  88.  
  89. cout<<trim(add(a,b))<<endl;
  90. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
1000000000000