image.png

解决思路

哈希表

  1. public String intToRoman(int num) {
  2. int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
  3. String[] strs = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
  4. StringBuilder res = new StringBuilder();
  5. for(int i = 0;i < values.length;i++){
  6. int a = num / values[i];
  7. if (a == 0)
  8. continue;
  9. for(int j = a;j > 0;j--)
  10. res.append(strs[i]);
  11. num -= (a * values[i]);
  12. if (num == 0)
  13. break;
  14. }
  15. return res.toString();
  16. }