Roman to Integer

来源:互联网 发布:上海国金网络朱文君 编辑:程序博客网 时间:2024/05/01 14:38

1.题目

给定一个罗马数字,将其转换成整数。

返回的结果要求在1到3999的范围内。

IV -> 4

XII -> 12

XXI -> 21

XCIX -> 99

2.算法

就是维护一个整数,如果1的下一位对应的位为5或10,则减去1,否则加上1,遇到5或者10就直接加上对应位的5或者10

   public int romanToInt(String s)     {        // Write your code here    if (s.length() < 1)    {    return 0;    }    int res = 0;    for (int i = 0; i < s.length(); i++)    {    switch (s.charAt(i))     {case 'I':if (i < s.length() - 1 && (s.charAt(i + 1) == 'V' || s.charAt(i + 1) == 'X')){res -= 1;}else{res += 1;}break;case 'V':res += 5;break;case 'X':if (i < s.length() - 1 && (s.charAt(i + 1) == 'L' || s.charAt(i + 1) == 'C')){res -= 10;}else{res += 10;}break;case 'L':res += 50;break;case 'C':if (i < s.length() - 1 && (s.charAt(i + 1) == 'D' || s.charAt(i + 1) == 'M')){res -= 100;}else{res += 100;}break;            case 'D':                  res += 500;                  break;              case 'M':                  res += 1000;                  break;default:return 0;}    }    return res;    }
 原文地址
 点击打开链接

0 0