fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4. #include <cmath>
  5. #include <cassert>
  6.  
  7. using namespace std;
  8.  
  9. class LargeInteger {
  10. private:
  11. static int nextLargeIntegerId;
  12. int id;
  13. int numDigits; // number of digits in LargeInt / size of alloc array
  14. int* digits; // the digits of the LargeInt we are representing
  15.  
  16. public:
  17. LargeInteger(int value);
  18. ~LargeInteger();
  19. string tostring();
  20. };
  21.  
  22. LargeInteger::LargeInteger(int value)
  23. {
  24. // set this instance id
  25. id = nextLargeIntegerId++;
  26.  
  27. numDigits = (int)log10(abs((double)value)) + 1;
  28.  
  29. // allocate an array of the right size
  30. digits = new int[numDigits];
  31.  
  32. // iterate through the digits in value, putting them into our
  33. // array of digits.
  34. int digit;
  35. for (int digitIndex = 0; digitIndex < numDigits; digitIndex++) {
  36. // least significant digit
  37. digit = value % 10;
  38. digits[digitIndex] = digit;
  39. cout << digit << "*";
  40.  
  41. // integer division to chop of least significant digit
  42. value = value / 10;
  43. }
  44. cout <<endl;
  45. }
  46.  
  47. LargeInteger::~LargeInteger()
  48. {
  49. cout << " destructor entered, freeing my digits" << endl
  50. << " id = " << id << endl
  51. //<< " value=" << tostring() // uncomment this after you implement tostring()
  52. << endl;
  53. delete[] this->digits;
  54. }
  55.  
  56. string LargeInteger::tostring()
  57. {
  58. string intValue;
  59. bool negative = false;
  60. for (int i=numDigits-1; i>=0; i--) {
  61. intValue += abs(digits[i]) + '0';
  62. if (digits[i]<0)
  63. negative = true;
  64. }
  65. if (negative)
  66. intValue.insert(0,1,'-');
  67. return intValue;
  68. }
  69.  
  70. int LargeInteger::nextLargeIntegerId = 0;
  71.  
  72. int main() {
  73. // test constructors, destructors and tostring()
  74. cout << "Testing Constructors, tostring() and destructor:" << endl;
  75. cout << "-------------------------------------------------------------" << endl;
  76. LargeInteger li1(-3483);
  77. cout << "li1 = " << li1.tostring() << endl;
  78.  
  79. return 0;
  80. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Testing Constructors, tostring() and destructor:
-------------------------------------------------------------
-3*-8*-4*-3*
li1 = -3483
 destructor entered, freeing my digits
 id = 0