必須考慮到補數…等情形。
We need to consider situations such as complements …etc.

ZeroJudge Link (Zh)

#include <stdio.h>
#include <math.h>
#include <string.h>

#define LENGTH 7
char roman[] = "IVXLCDM";
int base10[] = {1, 5, 10, 50, 100, 500, 1000};

int rom2Num(char *str);
void num2Rom(int num, char *out);

main() {
  char str1[100], str2[100], out[100];
  int iRes;
  while (scanf("%s", str1) != EOF && str1[0] != '#') {
    scanf("%s", str2);
    iRes = abs(rom2Num(str1) - rom2Num(str2));
    num2Rom(iRes, out);
    printf("%s\n", iRes ? out : "ZERO");
  }
  return 0;
}

int rom2Num(char *str) {
  int ptr, num = 0, isCom = 1;
  for (ptr = 0; ptr < strlen(str); ptr++) {
    if (ptr + 1 < strlen(str) &&
        strchr(roman, str[ptr]) < strchr(roman, str[ptr+1]))
      isCom = -1;
    else isCom = 1;
    num += isCom * base10[strchr(roman, str[ptr]) - roman];
  }
  return num;
}

void num2Rom(int num, char *out) {
  int i, repeat = 0;
  for (i = LENGTH-1; i >= 0; i--) {
    if (num >= base10[i]) {
      *(out++) = roman[i];
      num -= base10[i];
      i++; repeat++; continue;
    } else if (repeat >= 4) {
      if (*(out - 5) == roman[i+1]) {
        *(out -= 5) = roman[i];
        out++;
        *(out++) = roman[i+2];
      } else {
        *(out -= 3) = roman[i+1];
        out++;
      }
    }
    repeat = 0;
  }
  *out = '\0';
}