- LeetCode 13. Roman to Integer(Ja
- 12-13. Roman and Integer [Medium
- Leetcode PHP题解--D82 13. Roman to
- leetcode:13. Roman to Integer
- Leetcode13-Roman to Integer(Pyth
- LeetCode 13.Roman to Integer
- Leetcode 13. Roman to Integer
- LeetCode 13. Roman to Integer
- [LeetCode] 13. Roman to Integer
- LeetCode 13. Roman to Integer
题目:给定一个罗马数字,将其转换为整数。 保证输入在1到3999之间。
思路分析:
相邻两个罗马数字,如果前一个罗马数字(current )大于后一个罗马数字(after ),那么直接加上前一个数(current);如果前一个数小于后一个数,那么就加上前一个罗马数字的相反数(-current )。
编码实现也就分两种情况考虑:
①,如果当前数字大于之后的数字,则加上当前数字
②,其他情况则减去这个数字
代码实现如下:
public int romanToInt(String s) {
s = s+"*"; //为了方便处理最后一个字符
char[] chars = s.toCharArray();
int result = 0;
HashMap<Character, Integer> map = new HashMap<>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
map.put('*', Integer.MIN_VALUE);
int current = 0;
int after = 0;
int tmp = 0;
for (int i = 0; i < chars.length - 1; i++){
current = map.get(chars[i]);
after = map.get(chars[i+1]);
if (current < after){
current = -current;
}
result += current;
}
return result;
}
提交结果:
![](https://img.haomeiwen.com/i13521257/69aba7cf1b5c120e.png)
网友评论