[LeetCode] Roman to Integer

来源:互联网 发布:创建表的sql语句主键 编辑:程序博客网 时间:2024/04/28 04:31

问题

Given a roman numeral, convert it to an integer.

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

Subscribe to see which companies asked this question


思路

罗马数字的构造方式上一篇博客里面有提到,按照这个逻辑组织代码即可。


代码

public class Solution {    public int romanToInt(String s) {        int ret = charToNum(s.charAt(0));        for (int i = 1; i < s.length(); i++) {              if (charToNum(s.charAt(i-1)) < charToNum(s.charAt(i)))                ret += charToNum(s.charAt(i)) - 2*charToNum(s.charAt(i-1));              else                ret += charToNum(s.charAt(i));          }          return ret;      }        public int charToNum (char c) {          switch(c) {              case 'I': return 1;               case 'V': return 5;              case 'X': return 10;              case 'L': return 50;              case 'C': return 100;              case 'D': return 500;              case 'M': return 1000;              default: return 0;          }      } }


0 0