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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

【LeetCode】13. Roman to Integer

發布時間:2025/5/22 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode】13. Roman to Integer 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目:

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

提示:

此題只要熟悉羅馬數字的書寫語法,做起來就不會太難,關于羅馬數字的介紹可以參考這里。

代碼:

從左往右轉換的方法:

class Solution { public:int value(char c) {if (c == 'I') return 1;if (c == 'X') return 10;if (c == 'C') return 100;if (c == 'M') return 1000;if (c == 'V') return 5;if (c == 'L') return 50;if (c == 'D') return 500;}int romanToInt(string s) {if (s.size() == 0) return 0;if (s.size() == 1) return value(s[0]);int current, next, sum = 0, i = 0;for (; i < s.size() - 1; ++i) {current = value(s[i]);next = value(s[i+1]);sum += current < next ? -current : current;}sum += value(s[i]);return sum;} };

從右往左轉換的方法:

class Solution { public:int romanToInt(string s) {int res = 0;for (int i = s.length() - 1; i >= 0; i--) {char c = s[i];switch (c) {case 'I':res += (res >= 5 ? -1 : 1);break;case 'V':res += 5;break;case 'X':res += 10 * (res >= 50 ? -1 : 1);break;case 'L':res += 50;break;case 'C':res += 100 * (res >= 500 ? -1 : 1);break;case 'D':res += 500;break;case 'M':res += 1000;break;}}return res;} };

轉載于:https://www.cnblogs.com/jdneo/p/4755197.html

總結

以上是生活随笔為你收集整理的【LeetCode】13. Roman to Integer的全部內容,希望文章能夠幫你解決所遇到的問題。

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