欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode: Roman to Integer

发布时间:2023/12/10 编程问答 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 leetcode: Roman to Integer 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

http://oj.leetcode.com/problems/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 class Solution { 2 public: 3 int romanToInt(string s) { 4 int val = 0, mul = 0; 5 char one, five, ten; 6 const char *p = s.c_str(); 7 8 while (*p != '\0') { 9 char ch = *p; 10 11 if ('M' == ch) { 12 mul = 1000; 13 one = 'M'; 14 five = '?'; 15 ten = '?'; 16 } 17 else if (('C' == ch) || ('D' == ch)) { 18 mul = 100; 19 one = 'C'; 20 five = 'D'; 21 ten = 'M'; 22 } 23 else if (('X' == ch) || ('L' == ch)) { 24 mul = 10; 25 one = 'X'; 26 five = 'L'; 27 ten = 'C'; 28 } 29 else { // 'I' or 'V'. 30 mul = 1; 31 one = 'I'; 32 five = 'V'; 33 ten = 'X'; 34 } 35 36 int tmp; 37 38 if (one == ch) { 39 tmp = 1; 40 ++p; 41 while ((*p != '\0') && (one == *p)) { 42 ++tmp; 43 ++p; 44 } 45 46 if (ten == *p) { 47 val += (mul * 9); 48 ++p; 49 } 50 else if (five == *p) { 51 val += (mul * 4); 52 ++p; 53 } 54 else { 55 val += (mul * tmp); 56 } 57 } 58 else if (five == ch) { 59 tmp = 5; 60 ++p; 61 while ((*p != '\0') && (one == *p)) { 62 ++tmp; 63 ++p; 64 } 65 66 val += (mul * tmp); 67 } 68 // No need to handle ten, because it will be one in next level. 69 } 70 71 return val; 72 } 73 };

 

转载于:https://www.cnblogs.com/panda_lin/p/roman_to_integer.html

总结

以上是生活随笔为你收集整理的leetcode: Roman to Integer的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。