日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

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

编程问答

leetcode: Roman to Integer

發布時間:2023/12/10 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。