fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <math.h>
  5.  
  6. int const max = 'Z'-'A' + 1;
  7.  
  8. static char const*
  9. encode(char* buf, size_t bufsize, int n) {
  10. char* beg = buf;
  11. char* cur = buf+bufsize-1;
  12.  
  13. *beg = *cur = '\0';
  14.  
  15. while (n > 0 && cur > beg) {
  16. int r = (n%max);
  17. if (r == 0) {
  18. n /= max*2;
  19. r = max;
  20. } else
  21. n /= max;
  22. *(--cur) = 'A'-1+r;
  23. }
  24. return cur;
  25. }
  26.  
  27. static int
  28. decode(char const* str) {
  29. char const* beg = str;
  30. char const* end = beg+strlen(str)-1;
  31. int n = 0;
  32.  
  33. while (beg < end) {
  34. n += pow(max, end-beg) * (*beg-'A'+1);
  35. ++beg;
  36. }
  37. n += ((*end)-'A'+1);
  38. return n;
  39. }
  40.  
  41. int
  42. main(int argc, char* argv[]) {
  43. char buf[10];
  44.  
  45. printf("decode value: '%s' -> %d\n", "A", decode("A"));
  46. printf("decode value: '%s' -> %d\n", "Z", decode("Z"));
  47. printf("decode value: '%s' -> %d\n", "AA", decode("AA"));
  48. printf("decode value: '%s' -> %d\n", "DBA", decode("DBA"));
  49.  
  50. printf("encode value: %d -> '%s'\n", 2757, encode(buf, sizeof buf, 2757));
  51. printf("encode value: %d -> '%s'\n", 125, encode(buf, sizeof buf, 125));
  52.  
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0s 2008KB
stdin
Standard input is empty
stdout
decode value: 'A' -> 1
decode value: 'Z' -> 26
decode value: 'AA' -> 27
decode value: 'DBA' -> 2757
encode value: 2757 -> 'DBA'
encode value: 125 -> 'DU'