Pretty straight forward.
1 class Solution { 2 public: 3 string getRoman(int n, char ten, char five, char one) { 4 string result; 5 if (n == 9) { 6 result += one; 7 result += ten; 8 } else if (n >= 5) { 9 result += five; 10 while (n-- > 5) result += one; 11 } else if (n == 4) { 12 result += one; 13 result += five; 14 } else { 15 while (n-- > 0) result += one; 16 } 17 return result; 18 } 19 string intToRoman(int num) { 20 string result; 21 result = getRoman(num/1000%10, 0, 0, ‘M‘); 22 result += getRoman(num/100%10, ‘M‘, ‘D‘, ‘C‘); 23 result += getRoman(num/10%10, ‘C‘, ‘L‘, ‘X‘); 24 result += getRoman(num%10, ‘X‘, ‘V‘, ‘I‘); 25 return result; 26 } 27 };
时间: 2024-10-13 02:29:47