You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

54 lines
1.4 KiB

  1. #include <stdio.h>
  2. #include <string.h>
  3. /* DISCLAIMER: As far as I understand, I need to create a function,
  4. which takes a long long number (not a string), convert it to a
  5. string, use that string as it was a number in the source
  6. number system, and then print out in the target number system.
  7. I think it is way better to use string for the number itself and
  8. read it as a string from the beginning. But I will follow the
  9. assignment instructions since I don't want to get a lower grade.
  10. Please, make it more clear next time.
  11. */
  12. void convert(long long n, int s, int t) {
  13. if (!(s >= 2 && s <= 10 && t >= 2 && t <= 10)) {
  14. printf("cannot convert!\n");
  15. return;
  16. }
  17. // convert n from source number system to normal long long integer
  18. long long n_actual = 0, cur = 1;
  19. while (n) {
  20. if (n % 10 >= s) {
  21. printf("cannot convert!\n");
  22. return;
  23. }
  24. n_actual += cur * (n % 10);
  25. cur *= s;
  26. n /= 10;
  27. }
  28. // convert the actual n to target number system
  29. char buf[65];
  30. int i = 0;
  31. while (n_actual) {
  32. buf[i++] = (n_actual % t) + '0';
  33. n_actual /= t;
  34. }
  35. buf[i] = '\0';
  36. for (--i; i >= 0; --i) {
  37. putc(buf[i], stdout);
  38. }
  39. putc('\n', stdout);
  40. }
  41. int main() {
  42. long long number;
  43. int source, target;
  44. scanf("%lld%d%d", &number, &source, &target);
  45. convert(number, source, target);
  46. }