Tark_Wight

HITs.IE.V.t8

Jul 25th, 2024
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <iomanip>
  4.  
  5.  
  6. std::string transform(const std::string &binaryStr) {
  7.     std::string result;
  8.     for (char bit : binaryStr) {
  9.         if (bit == '0') {
  10.             result += "01";
  11.         } else if (bit == '1') {
  12.             result += "10";
  13.         }
  14.     }
  15.     return result;
  16. }
  17.  
  18. std::string toBinary(int num) {
  19.     std::string binaryStr;
  20.     while (num > 0) {
  21.         binaryStr = (num % 2 ? '1' : '0') + binaryStr;
  22.         num /= 2;
  23.     }
  24.     return binaryStr.empty() ? "0" : binaryStr;
  25. }
  26.  
  27. int binaryToDecimal(const std::string &binaryStr) {
  28.     int decimalValue = 0;
  29.     int base = 1;
  30.     for (int i = binaryStr.size() - 1; i >= 0; --i) {
  31.         if (binaryStr[i] == '1') {
  32.             decimalValue += base;
  33.         }
  34.         base *= 2;
  35.     }
  36.     return decimalValue;
  37. }
  38.  
  39. int main() {
  40.     const int maxNumber = 44;
  41.  
  42.     std::cout << std::left << std::setw(5) << "Odd Number"
  43.               << std::setw(20) << "Binary"
  44.               << std::setw(30) << "Transformed Binary"
  45.               << "Decimal Value\n";
  46.     std::cout << std::string(75, '-') << '\n';
  47.  
  48.     for (int i = 1; i <= maxNumber; i += 2) {
  49.         std::string binaryStr = toBinary(i);
  50.         std::string transformedBinaryStr = transform(binaryStr);
  51.         int decimalValue = binaryToDecimal(transformedBinaryStr);
  52.         std::cout << std::left << std::setw(15) << i
  53.                   << std::setw(20) << binaryStr
  54.                   << std::setw(30) << transformedBinaryStr
  55.                   << decimalValue << '\n';
  56.     }
  57.  
  58.     return 0;
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment