code.cpp 988 B

12345678910111213141516171819202122232425262728
  1. /* Create a function that takes an Arabic number and converts
  2. * it into a Roman number.
  3. * All roman numerals should be returned as uppercase.
  4. * The largest number that can be represented in this notation is 3,999.
  5. */
  6. // 1 = I, 4 = IV, 5 = V, 6 = VI, 9 = IX,
  7. // 10 = X, 50 = L , 100 = C , 500 = D , 1000 = M
  8. std::string convertToRoman(int num) {
  9. // array of int corresponding to roman numeral values
  10. int val[13] = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
  11. std::vector<std::string> roman = {"I","IV","V","IX","X","XL",
  12. "L","XC","C","CD","D","CM","M"};
  13. std::string r = "";
  14. int i = roman.size()-1;
  15. // starting with the biggest number, populate "r" with equivalent roman numeral
  16. while(num>0){
  17. // how many times to add the current letter(s)
  18. int fixIt = num/val[i];
  19. // add the current leter(s) to the string
  20. while(fixIt--){
  21. r += roman[i];
  22. }
  23. // replace the previous value of num with remainder
  24. num = num%val[i];
  25. i--;
  26. }
  27. return r;
  28. }