您的位置:首页 > 其它

#13 LeetCode——Roman to Integer

2015-09-28 17:19 543 查看

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

注:

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

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

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: