fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. /**
  6. Convert decimal number lying between 1-3999 to roman numerals
  7.  
  8. SYMBOL VALUE
  9. I 1
  10. II 2
  11. III 3
  12. IV 4
  13. V 5
  14. X 10
  15. L 50
  16. C 100
  17. D 500
  18. M 1000
  19. **/
  20.  
  21. //3999 - MMMCMXCIX
  22. string roman(int n){
  23. string s = "";
  24. int tho = n / 1000;
  25. while(tho--) {
  26. s= s+"M";
  27. }
  28. n = n % 1000;
  29. int hun = n / 100;
  30. if(hun == 9) {
  31. s+= "CM";
  32. } else if (hun >= 5) {
  33. s+= "D";
  34. while(hun-- > 5) {
  35. s+= "C";
  36. }
  37. } else {
  38. if(hun == 4) {
  39. s+= "CD";
  40. } else {
  41. while(hun--) {
  42. s += "C";
  43. }
  44. }
  45. }
  46.  
  47. n = n % 100;
  48. int ten = n / 10;
  49. if(ten == 9) {
  50. s+= "XC";
  51. } else if (ten >= 5) {
  52. s+="L";
  53. while(ten-- > 5) {
  54. s+="X";
  55. }
  56. } else {
  57. if(ten == 4) {
  58. s+= "XL";
  59. } else {
  60. while(ten --) {
  61. s+= "X";
  62. }
  63. }
  64. }
  65.  
  66. n = n % 10;
  67. if(n == 9) {
  68. s+= "IX";
  69. } else if (n >= 5) {
  70. s+= "V";
  71. while(n-- > 5) {
  72. s+= "I";
  73. }
  74. } else {
  75. if(ten == 4) {
  76. s+= "IV";
  77. } else {
  78. while(n--) {
  79. s+= "I";
  80. }
  81. }
  82. }
  83. return s;
  84.  
  85.  
  86. }
  87.  
  88. int main() {
  89. int intNum = 0;
  90. cin >> intNum;
  91. cout << roman(intNum);
  92. return 0;
  93. }
Success #stdin #stdout 0s 5296KB
stdin
3946
stdout
MMMCMXLVI