首页 > 代码库 > 13.罗马数字转成整形 Roman to Integer

13.罗马数字转成整形 Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.


  1. public class Solution {
  2. public int RomanCharToInt(char c)
  3. {
  4. switch (c)
  5. {
  6. case ‘I‘:
  7. return 1;
  8. case ‘V‘:
  9. return 5;
  10. case ‘X‘:
  11. return 10;
  12. case ‘L‘:
  13. return 50;
  14. case ‘C‘:
  15. return 100;
  16. case ‘D‘:
  17. return 500;
  18. case ‘M‘:
  19. return 1000;
  20. default:
  21. return 0;
  22. }
  23. }
  24. public int RomanToInt(string s)
  25. {
  26. int length = s.Length;
  27. int i = length - 1;
  28. int sum = RomanCharToInt(s[i--]);
  29. while (i >= 0)
  30. {
  31. if (RomanCharToInt(s[i + 1]) > RomanCharToInt(s[i]))
  32. {
  33. sum -= RomanCharToInt(s[i--]);
  34. }
  35. else
  36. {
  37. sum += RomanCharToInt(s[i--]);
  38. }
  39. }
  40. return sum;
  41. }
  42. }



来自为知笔记(Wiz)


13.罗马数字转成整形 Roman to Integer