public class Solution { public string IntToRoman(int num) { string[] M = { "", "M", "MM", "MMM" }; string[] C = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }; string[] X = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }; string[] I = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }; return M[num / 1000] + C[(num % 1000) / 100] + X[(num % 100) / 10] + I[num % 10]; } }
https://leetcode.com/problems/integer-to-roman/#/description
Java版本:
1 class Solution { 2 int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 3 String[] symbols = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; 4 5 public String intToRoman(int num) { 6 StringBuilder sb = new StringBuilder(); 7 // Loop through each symbol, stopping if num becomes 0. 8 for (int i = 0; i < values.length && num >= 0; i++) { 9 // Repeat while the current symbol still fits into num. 10 while (values[i] <= num) { 11 num -= values[i]; 12 sb.append(symbols[i]); 13 } 14 } 15 return sb.toString(); 16 } 17 }