Leetcode简单题罗马数字转整数
2017-09-16 14:39
549 查看
题目来源:https://leetcode.com/problems/roman-to-integer/description/
题目简单描述:要求输入[1,3999]范围的罗马数字,能转换成整数输出。
题目分析:
罗马数字罗马数字 | I | V | X | L | C | D | M |
整数 | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
规则:
相同的数字连写表示这些数字相加,如III表示3小的数字在大的数字左边,表示大的数字减去小的数字如IV表示数字4
小的数字在大的数字右边,表示全部相加,如VII表示为7
在一个数字上面画一条横线表示这个数字本身的值乘以1000,(此题中这种情况不予考虑)
解题思路:
从左往右按字符扫描,若当前字符数值大于或者等于他后面的字符数值,则sum=sum+此字符的值,否则,sum = sum-此字符的值对于最后一个字符,都是加在sum上的。
代码:
class Solution { public int romanToInt(String s) { char[] roman = s.toCharArray(); int sum = 0; int s1 =0,s2=0; Map<Character, Integer> m = new HashMap<Character,Integer>(){{ put('I', 1); put('V', 5); put('X', 10); put('L', 50); put('C', 100); put('D', 500); put('M', 1000); }}; for (int i = 0; i < roman.length-1; i++) { s1 = (int)m.get(roman[i]); s2 = (int)m.get(roman[i+1]); if (s1>=s2) { sum = sum +s1; } else { sum = sum-s1; } } sum += (int)m.get(roman[roman.length-1]); return sum; } }
相关文章推荐
- Leetcode : 13 罗马数字转整数
- LeetCode 12 Integer to Roman (整数转罗马数字)
- leetcode 罗马数字与整数的转换算法
- LeetCode 13. Roman to Integer -- 罗马数字转整数
- python解leetcode——13.Roman to Integer (罗马数字转为整数)
- [LeetCode] Integer to Roman 整数转化成罗马数字
- LeetCode 13. Roman to Integer 罗马数字转整数
- [LeetCode] 12. Integer to Roman 整数转为罗马数字
- (LeetCode) Roman to Integer --- 罗马数字转整数
- [LeetCode]12. Integer to Roman(整数转化为罗马数字)
- LeetCode习题笔记——罗马数字和整数之间的转换
- leetcode-12. Integer to Roman(整数转换成罗马数字)
- leetCode 12.Integer to Roman (整数转罗马数字) 解题思路和方法
- [LeetCode] 13. Roman to Integer 罗马数字转为整数
- leetcode:Integer to Roman(整数转化为罗马数字)
- LeetCode-13罗马数字转整数
- 【LeetCode-面试算法经典-Java实现】【013-Roman to Integer (罗马数字转成整数)】
- LeetCode : 12 整数转罗马数字 C++
- [LeetCode] Roman to Integer 罗马数字转化成整数
- leetcode 罗马数字与整数的转换算法