Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
1 public class Solution { 2 public int romanToInt(String s) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 StringBuffer ss = new StringBuffer(s); 6 int i,j; 7 int result = 0; 8 if(ss.length() == 0) return result; 9 else if(ss.length() == 1) return romanChar(ss.charAt(0)); 10 for(i = 0; i < ss.length(); i++){ 11 j = i + 1; 12 if(j == ss.length()){ 13 result += romanChar(ss.charAt(i)); 14 break; 15 } 16 if(leftLarger(ss.charAt(i),ss.charAt(j))){ 17 result += romanChar(ss.charAt(i)); 18 } 19 else{ 20 result += romanChar(ss.charAt(j)) - romanChar(ss.charAt(i)); 21 i ++; 22 23 } 24 } 25 return result; 26 } 27 28 public int romanChar(char c){ 29 if(c == 'I') return 1; 30 else if(c == 'V') return 5; 31 else if(c == 'X') return 10; 32 else if(c == 'L') return 50; 33 else if(c == 'C') return 100; 34 else if(c == 'D') return 500; 35 else if(c == 'M') return 1000; 36 else return -1; 37 } 38 public boolean leftLarger(char a,char b){ 39 if(a == 'M') return true; 40 if(a == 'D' && b != 'M') return true; 41 else if(a == 'C' && b != 'M' && b != 'D') return true; 42 else if(a == 'L' && b != 'M' && b != 'D' && b != 'C') return true; 43 else if(a == 'X' && b != 'M' && b != 'L' && b != 'D' && b != 'C' ) return true; 44 else if(a == 'V' && b != 'M' && b != 'X' && b != 'L' && b != 'D' && b != 'C') return true; 45 else if(a == 'I' && b == 'I') return true; 46 else return false; 47 } 48 }
posted on 2013-09-10 14:05 Step-BY-Step 阅读(151) 评论(0) 编辑 收藏 举报