fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <ctype.h>
  4. #include <stdlib.h>
  5.  
  6. static int const base = 26;
  7.  
  8. static int
  9. decode(char const* s) {
  10. int i=0, j, k;
  11. for (j=0, k=strlen(s); j < k; ++j) {
  12.  
  13. int m=s[j]-'A';
  14.  
  15. if (m < 0) return -1;
  16.  
  17. i = i*base + (m+1);
  18.  
  19. if (i < 0) return -2;
  20. }
  21. return i;
  22. }
  23.  
  24. static char const*
  25. encode(char* dst, size_t dstsz, int n) {
  26. char const* first = dst;
  27. char* last = dst+dstsz;
  28.  
  29. if (n <= 0) return NULL;
  30. if (first == last) return NULL;
  31.  
  32. *(--last) = '\0';
  33.  
  34. while (n-- > 0 && last > first) {
  35. *(--last) = 'A' + n%base;
  36. n = n / base;
  37. }
  38. return last;
  39. }
  40.  
  41. int
  42. main(void) {
  43. char line[128];
  44. char buf[10];
  45.  
  46. while (fscanf(stdin, "%s", line) != EOF) {
  47. printf("'%s' convert to ", line);
  48.  
  49. if (isalpha(line[0])) {
  50. int dec = decode(line);
  51. printf("'%d' <=> '%s'\n", dec, encode(buf, sizeof buf, dec));
  52. } else {
  53. char const* enc = encode(buf, sizeof buf, atoi(line));
  54. printf("'%s' <=> '%d'\n", enc, decode(enc));
  55. }
  56. }
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0s 2012KB
stdin
A
Z
AA
ZZ
DBA
AAZ
ZZZ
2757
125
stdout
'A' convert to '1' <=> 'A'
'Z' convert to '26' <=> 'Z'
'AA' convert to '27' <=> 'AA'
'ZZ' convert to '702' <=> 'ZZ'
'DBA' convert to '2757' <=> 'DBA'
'AAZ' convert to '728' <=> 'AAZ'
'ZZZ' convert to '18278' <=> 'ZZZ'
'2757' convert to 'DBA' <=> '2757'
'125' convert to 'DU' <=> '125'