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 @@ -329,28 +329,28 @@ end
329329
330330#### C
331331
332- ``` C
333-
334- int romanToInt (char * s) {
335- int map[ 26] = {0};
336- map[ 'I' - 'A'] = 1;
337- map[ 'V' - 'A'] = 5;
338- map[ 'X' - 'A'] = 10;
339- map[ 'L' - 'A'] = 50;
340- map[ 'C' - 'A'] = 100;
341- map[ 'D' - 'A'] = 500;
342- map[ 'M' - 'A'] = 1000;
343-
344- int res = 0, i = 0;
345- while (s[ i] ) {
346- int val = map[ s[ i] - 'A'] ;
347- int next = s[ i + 1] ? map[ s[ i + 1] - 'A'] : 0;
348- res += (val < next) ? -val : val;
349- i++;
350- }
351- return res;
332+ ``` c
333+ int nums (char c) {
334+ switch (c) {
335+ case 'I': return 1;
336+ case 'V': return 5;
337+ case 'X': return 10;
338+ case 'L': return 50;
339+ case 'C': return 100;
340+ case 'D': return 500;
341+ case 'M': return 1000;
342+ default: return 0;
343+ }
352344}
353345
346+ int romanToInt(char* s) {
347+ int ans = nums(s[ strlen(s) - 1] );
348+ for (int i = 0; i < (int) strlen(s) - 1; ++i) {
349+ int sign = nums(s[ i] ) < nums(s[ i + 1] ) ? -1 : 1;
350+ ans += sign * nums(s[ i] );
351+ }
352+ return ans;
353+ }
354354```
355355
356356<!-- tabs:end -->
You can’t perform that action at this time.
0 commit comments