您的位置:首页 > 其它

LeetCode—— 13. Roman to Integer

2018-03-23 13:12 232 查看

题目原址

https://leetcode.com/problems/roman-to-integer/description/

题目描述

Given a roman numeral, convert it to an integer.

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

解题思路

罗马数字一共有7个字母

MDCLXVI
1000500100501051
1. 将字符串每个字符转换为对应罗马数字代表的整数

2. 按照罗马数字的组合规则,如果前面的字符小于后面字符的值,则用后面的数减去前面的数为该罗马数字的整数值;如果前面的字符大于后面字符的值,则用后面的数加上前面的数为该罗马数字的整数值。如IV的值为4,VI的值为6

AC代码

class Solution {
public int romanToInt(String s) {
int ret = 0;
int[] a = new int[s.length()];
for(int i = 0; i < s.length(); i++) {
switch(s.charAt(i)) {
case 'M':
a[i] = 1000;
break;
case 'D':
a[i] = 500;
break;
case 'C':
a[i] = 100;
break;
case 'L':
a[i] = 50;
break;
case 'X':
a[i] = 10;
break;
case 'V':
a[i] = 5;
break;
case 'I':
a[i] = 1;
break;
}
}

for(int i = 0;i<s.length()-1;i++) {
if(a[i] < a[i+1])
ret -= a[i];
else
ret += a[i];
}
return ret + a[s.length()-1];
}
}


感谢

https://leetcode.com/problems/roman-to-integer/discuss/6509/7ms-solution-in-Java.-easy-to-understand
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: