Advertisement
AdrianMadajewski

Untitled

Mar 17th, 2019
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. #include "pch.h"
  2. #include <iostream>
  3. #include <string>
  4.  
  5. using std::string;
  6. using std::endl;
  7. using std::cout;
  8. using std::cin;
  9.  
  10. // Uppercase letters only
  11. string DecimalToBase(int number, int base) {
  12.     string pattern = "0123456789ABCDEFGHIJKLMOPQRSTUVWXYZ";
  13.     string result = "";
  14.  
  15.     while (number) {
  16.         result = pattern[number % base] + result;
  17.         number /= base;
  18.     }
  19.     return result;
  20. }
  21.  
  22. int handleHelp(char c) {
  23.     if (c >= 'A' & c <= 'Z')
  24.         return c - 55;
  25.     else if (c >= '0' && c <= '9')
  26.         return  c - 48; // '0';
  27.     else return -1;
  28. }
  29.  
  30. // Using Horner's method
  31. // returns - 1 when error occurs
  32. int BaseToDecimal(string number,  int size, int curr_base) {
  33.     int result = handleHelp(number[0]);
  34.     if(handleHelp(number[0]) < 0) return -1;
  35.     for (int i = 1; i < size; i++) {
  36.         if(handleHelp(number[i]) < 0) return -1;
  37.         result = result * curr_base + handleHelp(number[i]);
  38.     }
  39.     return result;
  40. }
  41.  
  42. int main()
  43. {
  44.     cout << "Program do zamiany systemow pozycyjnych.\n";
  45.     int number, base;
  46.     cout << "Podaj liczbe do zamiany: ";
  47.     cin >> number;
  48.     cout << "Podaj podstawe nowego systemu: ";
  49.     cin >> base;
  50.  
  51.     string res = DecimalToBase(number, base);
  52.  
  53.     cout << "Liczba - " << number << " - w systemie o podstawie - " << base << " - wynosi: ";
  54.     cout << res << endl;
  55.  
  56.     cout << "Twoja liczba to w systemie dziesietnym - " << BaseToDecimal(res, res.size(), base) << endl;
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement