dzungchaos

C++ "Chuyển hệ cơ số (dùng stack)"

Jan 15th, 2020
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. typedef struct intStack {
  5.     int * stackArr;
  6.     int count;
  7.     int top;
  8.     int stackMax;
  9. } intStack;
  10.  
  11. intStack* creatStack(int max){
  12.     intStack* stack;
  13.     stack = new intStack;
  14.     if (stack == NULL)
  15.         return 0;
  16.     stack->stackArr = new int[max];
  17.     stack->count = 0;
  18.     stack->top = -1;
  19.     stack->stackMax = max;
  20.     return stack;  
  21. }
  22.  
  23. void destroyStack(intStack* stack){
  24.     delete [] stack->stackArr;
  25.     delete stack;
  26. }
  27.  
  28. int pushStack(intStack* stack, int val){
  29.     if (stack->count == stack->stackMax)
  30.         return 0;
  31.     (stack->count)++;
  32.     (stack->top)++;
  33.     stack->stackArr[stack->top] = val;
  34.     return 1;
  35. }
  36.  
  37. int popStack(intStack* stack, int* val){
  38.     if (stack->count == 0)
  39.         return 0;
  40.     *val = stack->stackArr[stack->top];
  41.     (stack->count)--;
  42.     (stack->top)--;
  43.     return 1;
  44. }
  45.  
  46. int topStack(intStack* stack, int* val){
  47.     if (stack->count == 0)
  48.         return 0;
  49.     *val = stack->stackArr[stack->top];
  50.     return 1;
  51. }
  52.  
  53. int isEmpty(intStack* stack){
  54.     return !(stack->count);
  55. }
  56.  
  57. int isFull(intStack* stack){
  58.     return (stack->count == stack->stackMax);
  59. }
  60.  
  61. void printStack(intStack* stack){
  62.     for(int i = 0; i < stack->count; i++)
  63.         cout << stack->stackArr[i] << " ";
  64.     cout << endl;
  65. }
  66.  
  67. void baseChange(int n, int b){
  68.     char* digits = "0123456789ABCDEF";
  69.     intStack* stack = creatStack(100);
  70.     while (n) {
  71.         pushStack(stack, n % b);
  72.         n /= b;
  73.     }
  74.     while(!isEmpty(stack)){
  75.         int temp;
  76.         popStack(stack, & temp);
  77.         cout << digits[temp];
  78.     }
  79.     cout << endl;
  80.     destroyStack(stack);
  81. }
  82.  
  83. int main(){
  84.     int n, b;
  85.     cin >> n >> b;
  86.     baseChange(n , b);
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment