File tree Expand file tree Collapse file tree 1 file changed +20
-20
lines changed
solution/0000-0099/0013.Roman to Integer Expand file tree Collapse file tree 1 file changed +20
-20
lines changed Original file line number Diff line number Diff line change @@ -343,28 +343,28 @@ end
343343
344344#### C
345345
346- ``` C
347-
348- int romanToInt (char * s) {
349- int map[ 26] = {0};
350- map[ 'I' - 'A'] = 1;
351- map[ 'V' - 'A'] = 5;
352- map[ 'X' - 'A'] = 10;
353- map[ 'L' - 'A'] = 50;
354- map[ 'C' - 'A'] = 100;
355- map[ 'D' - 'A'] = 500;
356- map[ 'M' - 'A'] = 1000;
357-
358- int res = 0, i = 0;
359- while (s[ i] ) {
360- int val = map[ s[ i] - 'A'] ;
361- int next = s[ i + 1] ? map[ s[ i + 1] - 'A'] : 0;
362- res += (val < next) ? -val : val;
363- i++;
364- }
365- return res;
346+ ``` c
347+ int nums (char c) {
348+ switch (c) {
349+ case 'I': return 1;
350+ case 'V': return 5;
351+ case 'X': return 10;
352+ case 'L': return 50;
353+ case 'C': return 100;
354+ case 'D': return 500;
355+ case 'M': return 1000;
356+ default: return 0;
357+ }
366358}
367359
360+ int romanToInt(char* s) {
361+ int ans = nums(s[ strlen(s) - 1] );
362+ for (int i = 0; i < (int) strlen(s) - 1; ++i) {
363+ int sign = nums(s[ i] ) < nums(s[ i + 1] ) ? -1 : 1;
364+ ans += sign * nums(s[ i] );
365+ }
366+ return ans;
367+ }
368368```
369369
370370<!-- tabs:end -->
You can’t perform that action at this time.
0 commit comments