Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路分析:
1、熟悉罗马数字的规则。见LeetCode之Easy篇 ——(12)Integer to Roman
2、将输入的罗马数字转化成数组,并逐一通过case比对,然后根据其规则进行运算。
Java代码示例:
class Solution { public int romanToInt(String s) { char[] letters = s.toCharArray(); int[] nums = new int[letters.length]; int answer=0; for(int i = 0; i<letters.length; i++){ switch(letters[i]){ case ‘M‘: nums[i]=1000;break; case ‘D‘: nums[i]=500;break; case ‘C‘: nums[i]=100;break; case ‘L‘: nums[i]=50;break; case ‘X‘: nums[i]=10;break; case ‘V‘: nums[i]=5;break; case ‘I‘: nums[i]=1;break; } } for(int i=0; i<nums.length-1;i++){ if(nums[i]>=nums[i+1]) answer+=nums[i]; else answer-=nums[i]; } answer+=nums[nums.length-1]; return answer; } }