fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void populateRomanChar(unordered_map<int, string>& numberToRomanCharMap) {
  5. numberToRomanCharMap[1000] = "M";
  6. numberToRomanCharMap[900] = "CM";
  7. numberToRomanCharMap[500] = "D";
  8. numberToRomanCharMap[400] = "CD";
  9. numberToRomanCharMap[100] = "C";
  10. numberToRomanCharMap[90] = "XC";
  11. numberToRomanCharMap[50] = "L";
  12. numberToRomanCharMap[40] = "XL";
  13. numberToRomanCharMap[10] = "X";
  14. numberToRomanCharMap[9] = "IX";
  15. numberToRomanCharMap[5] = "V";
  16. numberToRomanCharMap[4] = "IV";
  17. numberToRomanCharMap[1] = "I";
  18. }
  19.  
  20. string convertToRoman(int number) {
  21.  
  22. string romanNumber = "";
  23. unordered_map<int, string> numberToRomanCharMap;
  24. populateRomanChar(numberToRomanCharMap);
  25. while(number > 0) {
  26.  
  27. int tempNum = INT_MIN;
  28. for(auto num: numberToRomanCharMap) {
  29. if(num.first <= number) {
  30. tempNum = max(tempNum, num.first);
  31. }
  32. }
  33. romanNumber += numberToRomanCharMap[tempNum];
  34. number -= tempNum;
  35.  
  36. }
  37. return romanNumber; // "MCMIV", "XL",
  38.  
  39. }
  40.  
  41. int main() {
  42. vector<int> num{2994, 1904, 40, 75};
  43. for(auto x: num) {
  44. cout << "Equivalent Roman Numeral: " << convertToRoman(x) << endl;
  45. }
  46. return 0;
  47. }
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
Equivalent Roman Numeral: MMCMXCIV
Equivalent Roman Numeral: MCMIV
Equivalent Roman Numeral: XL
Equivalent Roman Numeral: LXXV