#13 LeetCode——Roman to Integer

来源:互联网 发布:druid优化 编辑:程序博客网 时间:2024/04/30 00:36

将罗马字符转化为阿拉伯数字表示

注:
罗马数字表示:I(1)、V(5)、X(10)、L(50)、C(100)、D(500)、 M(1000)

阿拉伯数字 罗马数字 1 I 4 IV 5 V 9 IX 10 X 50 L 100 V 500 D 1000 M

java代码如下

public class Solution {    public int romanToInt(String s) {        char[] nums = s.toCharArray();        int result = 0;        int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };          for (int i = 0; i < nums.length; i++)         {               //1000            if(nums[i] == 'M')            {                result += 1000;            }            //100            if(nums[i] == 'C' && i + 1 < nums.length)            {                if(nums[i + 1] == 'M' || nums[i + 1] == 'D')                {                    result -= 100;                }                else                {                    result += 100;                }            }            else if(nums[i] == 'C')            {                result += 100;            }            //500            if(nums[i] == 'D')            {                result += 500;            }            //10            if(nums[i] == 'X' && i + 1 < nums.length)            {                if(nums[i + 1] == 'C' || nums[i + 1] == 'L')                {                    result -= 10;                }                else                {                    result += 10;                }            }            else if(nums[i] == 'X')            {                result += 10;            }            //50            if(nums[i] == 'L')            {                result += 50;            }            //1            if(nums[i] == 'I' && i + 1 < nums.length)            {                if(nums[i + 1] == 'X' || nums[i + 1] == 'V')                {                    result -= 1;                }                else                {                    result += 1;                }            }            else if(nums[i] == 'I')            {                result += 1;            }            //5            if(nums[i] == 'V')            {                result += 5;            }        }        return result;    }}

0 0
原创粉丝点击