搜索此博客

2012年8月27日星期一

Roman to Integer

This problem, in contrast to the previous one, convert a roman number back to an integer, and is not that straightforward. The main idea is to group the roman characters together which can be convert to a valid integer.

The main idea is to group the roman characters properly. This requires a careful manipulation of strings. Also, a hash table is needed for look-up.

001 public int romanToInt(String s) {
002     String[]digits={"I","II","III","IV","V","VI","VII","VIII","IX"};
003     String[]tens={"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
004     String[]hundreds={"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
005     String[]thousands={"M","MM","MMM"};
006   
007     Hashtable<String,Integer> ht=new Hashtable<String,Integer>();
008 
009     for(int i=0;i<3;i++)
010     {
011         ht.put(thousands[i],(i+1)*1000);
012     }
013   
014     for(int i=0;i<9;i++)
015     {
016         ht.put(hundreds[i],(i+1)*100);
017     }
018   
019     for(int i=0;i<9;i++)
020     {
021         ht.put(tens[i],(i+1)*10);
022     }
023   
024     for(int i=0;i<9;i++)
025     {
026         ht.put(digits[i],i+1);
027     }
028   
029     int result=0;
030   
031     char[] str=s.toCharArray();
032     int i=0;
033     int start=0;
034   
035     if(str[i]=='M')
036     {
037         while(str[i]=='M' )
038         {
039             i++;
040             if(i==str.length)
041             {
042                 break;
043             }                                  
044         }
045       
046         if(i>start)
047         {
048             int thousand=ht.get(s.substring(start,i));
049             result+=thousand;
050             start=i;
051         }          
052     }
053   
054     if(i<str.length && (str[i]=='C'||str[i]=='D'))
055     {
056         while(str[i]=='C'||str[i]=='D'||str[i]=='M')
057         {
058             i++;
059             if (i==str.length)
060             {
061                 break;
062             }              
063         }
064       
065         if(i>start)
066         {
067             int hundred=ht.get(s.substring(start,i));
068             result+=hundred;
069             start=i;
070         }          
071     }
072   
073     if(i<str.length && (str[i]=='X'||str[i]=='L'))
074     {
075         while(str[i]=='X'||str[i]=='L'||str[i]=='C')
076         {
077             i++;
078             if (i==str.length)
079             {
080                 break;
081             }              
082         }
083       
084         if(i>start)
085         {
086             int ten=ht.get(s.substring(start,i));
087             result+=ten;
088             start=i;
089         }
090       
091     }
092   
093     while(i<str.length)
094     {
095         i++;
096     }
097     if(i>start)
098     {
099         int digit=ht.get(s.substring(start,i));
100         result+=digit;
101     }
102                 
103     return result;
104 }

没有评论:

发表评论