fork download
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3. #include <string.h>
  4.  
  5. const char* units[] = {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"};
  6. const char* tens[] = {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "C"};
  7. const char* hundreds[] = {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "M"};
  8. const char* symbols = "IVXLCDM";
  9.  
  10. void to_roman(int number, char *result);
  11. bool has_one(const char *haystack, char needle);
  12. int main(void)
  13. {
  14. for(int number = 1; number < 2000; number++)
  15. {
  16. bool ok = true;
  17. char roman[100];
  18. to_roman(number, roman);
  19. for(int s = 0; symbols[s]; s++)
  20. {
  21. if(!has_one(roman, symbols[s]))
  22. {
  23. ok = false;
  24. break;
  25. }
  26. }
  27. if(ok)
  28. printf("%d : %s\n", number, roman);
  29. }
  30. return 0;
  31. }
  32.  
  33. bool has_one(const char *haystack, char needle)
  34. {
  35. int count = 0;
  36. for(int i = 0; haystack[i]; i++)
  37. if(haystack[i] == needle && ++count == 2)
  38. return false;
  39. return count == 1;
  40. }
  41.  
  42. void to_roman(int number, char *result)
  43. {
  44. int M = (number / 1000) % 10;
  45. int C = (number / 100) % 10;
  46. int X = (number / 10) % 10;
  47. int I = (number / 1) % 10;
  48. result[0] = '\0';
  49. if(M != 0)
  50. strcat(result, "M");
  51. if(C != 0)
  52. strcat(result, hundreds[C - 1]);
  53. if(X != 0)
  54. strcat(result, tens[X - 1]);
  55. if(I != 0)
  56. strcat(result, units[I - 1]);
  57. }
Success #stdin #stdout 0s 10320KB
stdin
Standard input is empty
stdout
1444 : MCDXLIV
1446 : MCDXLVI
1464 : MCDLXIV
1466 : MCDLXVI
1644 : MDCXLIV
1646 : MDCXLVI
1664 : MDCLXIV
1666 : MDCLXVI