Hamoudi30

bonusQ

Nov 10th, 2021 (edited)
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.79 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. char ConvertToChar (int num) {
  4.   if (num >= 0 && num <= 9)
  5.     return char(num + '0');
  6.   else
  7.     return char(num - 10 + 'A');
  8. }
  9. void ReverseString(char *str) {
  10.   int sz = strlen(str);
  11.   for (int i = 0; i < sz / 2; i++) {
  12.     char cur_char = str[i];
  13.     str[i] = str[sz - i - 1];
  14.     str[sz - i - 1] = cur_char;
  15.   }
  16. }
  17. char* FromDecToBase(int num, int base, char res[], int index) {
  18.   // base case
  19.   if (num <= 0) {
  20.     res[index] = '\0';
  21.     ReverseString(res);
  22.     return res;
  23.   }
  24.   // recursive case
  25.   res[index] = ConvertToChar(num % base);
  26.   FromDecToBase(num / base, base, res, index + 1);
  27. }
  28. int main() {
  29.   int num, base;
  30.   scanf("%d%d", &num, &base);
  31.   char res[1000];
  32.   printf("%s", FromDecToBase(num, base, res, 0));
  33.   return 0;
  34. }
  35.  
Add Comment
Please, Sign In to add comment