x3c2c5

Untitled

Mar 13th, 2023
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <cmath>
  4.  
  5. using namespace std;
  6.  
  7. class Integer {
  8. private:
  9.     int base;
  10.     string number;
  11.  
  12. public:
  13.     // конструктор
  14.     Integer(int base, string number) {
  15.         this->base = base;
  16.         this->number = number;
  17.     }
  18.  
  19.     // деструктор
  20.     ~Integer() {}
  21.  
  22.     // getters
  23.     int getBase() {
  24.         return base;
  25.     }
  26.  
  27.     string getNumber() {
  28.         return number;
  29.     }
  30.  
  31.     // сеттери
  32.     void setBase(int base) {
  33.         this->base = base;
  34.     }
  35.  
  36.     void setNumber(string number) {
  37.         this->number = number;
  38.     }
  39.  
  40.     // конвертацiя в десяткову систему числення
  41.     int toDecimal() {
  42.         int decimal = 0;
  43.         int power = 0;
  44.         for (int i = number.length() - 1; i >= 0; i--) {
  45.             int digit = 0;
  46.             if (isdigit(number[i])) {
  47.                 digit = number[i] - '0';
  48.             } else {
  49.                 digit = number[i] - 'A' + 10;
  50.             }
  51.             decimal += digit * pow(base, power);
  52.             power++;
  53.         }
  54.         return decimal;
  55.     }
  56.  
  57.     // конвертацiя  з десяткової системи числення
  58.     void fromDecimal(int decimal) {
  59.         string result = "";
  60.         while (decimal > 0) {
  61.             int remainder = decimal % base;
  62.             if (remainder < 10) {
  63.                 result = to_string(remainder) + result;
  64.             } else {
  65.                 result = char(remainder - 10 + 'A') + result;
  66.             }
  67.             decimal /= base;
  68.         }
  69.         number = result;
  70.     }
  71. };
  72.  
  73. int main() {
  74.     Integer num(16, "7FF");
  75.     cout << "Base: " << num.getBase() << endl;
  76.     cout << "Number: " << num.getNumber() << endl;
  77.     cout << "Decimal: " << num.toDecimal() << endl;
  78.  
  79.     num.setBase(2);
  80.     num.fromDecimal(2047);
  81.     cout << "Base: " << num.getBase() << endl;
  82.     cout << "Number: " << num.getNumber() << endl;
  83.  
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment