1+ package  leetcode .editor .en ;
2+ 3+ import  java .util .*;
4+ 5+ class  RomanToInteger  {
6+ 7+ //leetcode submit region begin(Prohibit modification and deletion) 
8+ class  Solution  {
9+  public  int  romanToInt (String  s ) {
10+  int  start  = 0 , out  = 0 ;
11+  RomanDigit [][] ordersOfMagnitude  = new  RomanDigit [][]{
12+  RomanDigit .THOUSANDS , RomanDigit .HUNDREDS , RomanDigit .TENS , RomanDigit .ONES 
13+  };
14+  for  (RomanDigit [] choices  : ordersOfMagnitude ) {
15+  for  (RomanDigit  digit  : choices ) {
16+  if  (digit .text .equals (safeSubstring (s , start , start  + digit .length ))) {
17+  out  += digit .value ;
18+  start  += digit .length ;
19+  break ;
20+  }
21+  }
22+  }
23+  return  out ;
24+  }
25+  private  String  safeSubstring (String  s , int  start , int  end ){
26+  if (end  > s .length ()) return  null ;
27+  return  s .substring (start , end );
28+  }
29+  private  record  RomanDigit (
30+  String  text ,
31+  int  length ,
32+  int  value 
33+  ){
34+  final  static  RomanDigit [] ONES  = new  RomanDigit []{
35+  new  RomanDigit ("III" , 3 , 3 ),
36+  new  RomanDigit ("II" , 2 , 2 ),
37+  new  RomanDigit ("IV" , 2 , 4 ),
38+  new  RomanDigit ("IX" , 2 , 9 ),
39+  new  RomanDigit ("VIII" , 4 , 8 ),
40+  new  RomanDigit ("VII" , 3 , 7 ),
41+  new  RomanDigit ("VI" , 2 , 6 ),
42+  new  RomanDigit ("V" , 1 , 5 ),
43+  new  RomanDigit ("I" , 1 , 1 )
44+  };
45+  final  static  RomanDigit [] TENS  = new  RomanDigit []{
46+  new  RomanDigit ("XXX" , 3 , 30 ),
47+  new  RomanDigit ("XX" , 2 , 20 ),
48+  new  RomanDigit ("XC" , 2 , 90 ),
49+  new  RomanDigit ("XL" , 2 , 40 ),
50+  new  RomanDigit ("LXXX" , 4 , 80 ),
51+  new  RomanDigit ("LXX" , 3 , 70 ),
52+  new  RomanDigit ("LX" , 2 , 60 ),
53+  new  RomanDigit ("L" , 1 , 50 ),
54+  new  RomanDigit ("X" , 1 , 10 )
55+  };
56+  final  static  RomanDigit [] HUNDREDS  = new  RomanDigit []{
57+  new  RomanDigit ("CCC" , 3 , 300 ),
58+  new  RomanDigit ("CC" , 2 , 200 ),
59+  new  RomanDigit ("CM" , 2 , 900 ),
60+  new  RomanDigit ("CD" , 2 , 400 ),
61+  new  RomanDigit ("DCCC" , 4 , 800 ),
62+  new  RomanDigit ("DCC" , 3 , 700 ),
63+  new  RomanDigit ("DC" , 2 , 600 ),
64+  new  RomanDigit ("D" , 1 , 500 ),
65+  new  RomanDigit ("C" , 1 , 100 )
66+  };
67+  final  static  RomanDigit [] THOUSANDS  = new  RomanDigit []{
68+  new  RomanDigit ("MMM" , 3 , 3000 ),
69+  new  RomanDigit ("MM" , 2 , 2000 ),
70+  new  RomanDigit ("M" , 1 , 1000 )
71+  };
72+ 73+  }
74+ }
75+ //leetcode submit region end(Prohibit modification and deletion) 
76+ 77+ }
0 commit comments