fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using std::string;
  5.  
  6. int CTOI(char a)
  7. {
  8. return a - 48;
  9. }
  10.  
  11. char ITOC(int a)
  12. {
  13. if (a == 0)
  14. return '0';
  15. return a + '0';
  16. }
  17.  
  18. int creDec(int a, int b)
  19. {
  20. return (a * 10) + b;
  21. }
  22.  
  23. string divide2(string str)
  24. {
  25. string ret; // Object to be returned.
  26. int rem = 0; // Keep track of remainders.
  27.  
  28. // Iterate over the characters of the input string.
  29. auto iter = str.begin();
  30. auto end = str.end();
  31. for ( ; iter != end; ++iter )
  32. {
  33. int n1 = CTOI(*iter); // The number from the string.
  34. int n2 = creDec(rem, n1); // The number after we account for the remainder.
  35. int n3 = n2/2; // Result of the division.
  36. rem = n2%2; // Remainder of the division.
  37.  
  38. if ( ret.empty() && n3 == 0 )
  39. {
  40. // Do nothing. There is no need to addd leading zeros to ret.
  41. }
  42. else
  43. {
  44. // Add the character corresponding to n3 to ret.
  45. ret.push_back(ITOC(n3));
  46. }
  47. }
  48.  
  49. // If the return value is an empty string, return "0".
  50. if ( ret.empty() )
  51. {
  52. return "0";
  53. }
  54. else
  55. {
  56. return ret;
  57. }
  58. }
  59.  
  60. void test(string const& in)
  61. {
  62. std::cout << "Result of dividing " << in << " by 2 is: " << divide2(in) << std::endl;
  63. }
  64.  
  65. int main()
  66. {
  67. test("0");
  68. test("1");
  69. test("2");
  70. test("3");
  71. test("1183");
  72. test("000000000");
  73. test("36032092435013184350131843501318435013184350131843501318");
  74. }
  75.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Result of dividing 0 by 2 is: 0
Result of dividing 1 by 2 is: 0
Result of dividing 2 by 2 is: 1
Result of dividing 3 by 2 is: 1
Result of dividing 1183 by 2 is: 591
Result of dividing 000000000 by 2 is: 0
Result of dividing 36032092435013184350131843501318435013184350131843501318 by 2 is: 18016046217506592175065921750659217506592175065921750659