【13】Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
罗马数字转换成阿拉伯数字
Subscribe to see which companies asked this question
思路:
罗马数字的对应关系:I(1)、V(5)、X(10)、L(50)、C(100)、D(500)、M(1000)
1~9 : String[] num1 = {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
10~90: String[] num2 = {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
100~ 900: String[] num3 = {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
1000、2000、3000 : String[] num4 = {"M", "MM", "MMM"};
通过观察各个数字的规律可以发现,两个不同的数字组合时,位于大数的后面时就作为加数;位于大数的前面就作为减数,例如Ⅲ=3,Ⅳ=4,Ⅵ=6,ⅩⅨ=19,ⅩⅩ=20,ⅩLⅤ=45,MCMⅩⅩC=1980
所有的数字组合中一共有6个这样的数字组合:"IV"、"IX"、"XL"、"XC"、"CD","CM",最后要求的罗马数字其实就是简单的每一位映射出来的数字相加即可,但是对于这6个数字要特殊处理下(使用前6个if从句),首先要减去自身(抵消掉第二个for循环里单个数字),然后让位于它后面的大数减去自身,所以需要减去自身两次
public int romanToInt(String s) { int sum=0; if(s.indexOf("IV")!=-1){sum-=2;} if(s.indexOf("IX")!=-1){sum-=2;} if(s.indexOf("XL")!=-1){sum-=20;} if(s.indexOf("XC")!=-1){sum-=20;} if(s.indexOf("CD")!=-1){sum-=200;} if(s.indexOf("CM")!=-1){sum-=200;} char c[]=s.toCharArray(); int count=0; for(;count<=s.length()-1;count++){ if(c[count]=='M') sum+=1000; if(c[count]=='D') sum+=500; if(c[count]=='C') sum+=100; if(c[count]=='L') sum+=50; if(c[count]=='X') sum+=10; if(c[count]=='V') sum+=5; if(c[count]=='I') sum+=1; } return sum; }
//方法二 public class Solution { public int romanToInt(String s) { //:Ⅰ(1)Ⅴ(5)Ⅹ(10)L(50)C(100)D(500)M(1000) // rules:位于大数的后面时就作为加数;位于大数的前面就作为减数 //eg:Ⅲ=3,Ⅳ=4,Ⅵ=6,ⅩⅨ=19,ⅩⅩ=20,ⅩLⅤ=45,MCMⅩⅩC=1980 //"DCXXI" if(s == null || s.length() == 0) return 0; int len = s.length(); HashMap<Character,Integer> map = new HashMap<Character,Integer>(); 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); int result = map.get(s.charAt(len -1)); int pivot = result; for(int i = len -2; i>= 0;i--){ int curr = map.get(s.charAt(i)); if(curr >= pivot){ result += curr; }else{ result -= curr; } pivot = curr; } return result; } }