Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
I = 1;
V = 5;
X = 10;
L = 50;
C = 100;
D = 500;
M = 1000;
参考C++:http://www.cnblogs.com/easonliu/p/3654182.html
解释一下罗马计算的规律。当下一个的值大于前一个的值,就减去前一个值。如CD=500-100=400。
如下代码是我自己编写的,但是因为算法太大,导致Time Limit Exceeded。不过还是先记录下这个繁重的算法,这几天再看看能不能精简一下。
1 public class Solution { 2 public int romanToInt(String s) { 3 //String []value={"I","V","X","L","C","D","M"}; 4 char []value={‘I‘,‘V‘,‘X‘,‘L‘,‘C‘,‘D‘,‘M‘}; 5 int []a ={1,5,10,50,100,500,1000}; 6 int num=0; 7 for(int i=0;i<s.length();i++){ 8 for(int j=0;j<value.length;j++){ 9 if(s.charAt(i)==value[j]){ 10 if(i+1<s.length()){ 11 for(int k=0;k<value.length;k++){ 12 if(s.charAt(i+1)==value[k]){ 13 if(a[j]<a[k]) 14 //比较的是整型int值,而不是字符的大小,因而要转换 15 //if(s.charAt(i)<s.charAt(i+1)){ 16 num=num-a[j];//当后一个的值大于前一个值,减去前一个值 17 else 18 num=num+a[j]; 19 } 20 } 21 }else 22 num=num+a[j]; 23 } 24 25 } 26 27 } 28 System.out.println(num); 29 return num; 30 } 31 }
原文:http://www.cnblogs.com/anylemons/p/6476724.html