File tree Expand file tree Collapse file tree 1 file changed +18
-16
lines changed
solution/0000-0099/0013.Roman to Integer Expand file tree Collapse file tree 1 file changed +18
-16
lines changed Original file line number Diff line number Diff line change 1- int romanToInt (char * s ) {
2- int map [26 ] = {0 };
3- map ['I' - 'A' ] = 1 ;
4- map ['V' - 'A' ] = 5 ;
5- map ['X' - 'A' ] = 10 ;
6- map ['L' - 'A' ] = 50 ;
7- map ['C' - 'A' ] = 100 ;
8- map ['D' - 'A' ] = 500 ;
9- map ['M' - 'A' ] = 1000 ;
1+ int nums (char c ) {
2+ switch (c ) {
3+ case 'I' : return 1 ;
4+ case 'V' : return 5 ;
5+ case 'X' : return 10 ;
6+ case 'L' : return 50 ;
7+ case 'C' : return 100 ;
8+ case 'D' : return 500 ;
9+ case 'M' : return 1000 ;
10+ default : return 0 ;
11+ }
12+ }
1013
11- int res = 0 , i = 0 ;
12- while (s [i ]) {
13- int val = map [s [i ] - 'A' ];
14- int next = s [i + 1 ] ? map [s [i + 1 ] - 'A' ] : 0 ;
15- res += (val < next ) ? - val : val ;
16- i ++ ;
14+ int romanToInt (char * s ) {
15+ int ans = nums (s [strlen (s ) - 1 ]);
16+ for (int i = 0 ; i < (int ) strlen (s ) - 1 ; ++ i ) {
17+ int sign = nums (s [i ]) < nums (s [i + 1 ]) ? -1 : 1 ;
18+ ans += sign * nums (s [i ]);
1719 }
18- return res ;
20+ return ans ;
1921}
You can’t perform that action at this time.
0 commit comments