Roman to Integer - LeetCode
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
首先要知道罗马数字的规律。 罗马数字对应阿拉伯数字有两种情况:
1.用两个字符来表示一个数字,这种情况发生在当第一个字符小于第二个字符的时候: IV, IX...
2. 用一个字符表示一个数字。III, V, X
所以,解题的思路就是从后往前扫,如果i-1小于i,那么这就是第一种情况,只要将第二个字符表示的数字减去第一个字符表示的数字。如果i-1不小于i,那么就是第二种情况。
1 public class Solution { 2 public int romanToInt(String s) { 3 if(s==null||s.length()==0) return 0; 4 int d=s.length()-1; 5 int res=0; 6 while(d>=0){ 7 if(d-1>=0&&charToNum(s.charAt(d))>charToNum(s.charAt(d-1))){ 8 res+=charToNum(s.charAt(d))-charToNum(s.charAt(d-1)); 9 d-=2; 10 }else{ 11 res+=charToNum(s.charAt(d)); 12 d--; 13 } 14 return res; 15 } 16 } 17 18 public int chatToNum(char c){ 19 switch(c){ 20 case 'I': return 1; 21 case 'V': return 5; 22 case 'X': return 10; 23 case 'L':return 50; 24 case 'C': return 100; 25 case 'D': return 500; 26 case 'M': return 1000; 27 } 28 return 0; 29 } 30 }