日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

【LeetCode】13. Roman to Integer

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

題目:

Given a roman numeral, convert it to an integer.

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

提示:

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

代碼:

從左往右轉(zhuǎn)換的方法:

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;} };

從右往左轉(zhuǎn)換的方法:

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;} };

轉(zhuǎn)載于:https://www.cnblogs.com/jdneo/p/4755197.html

總結(jié)

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

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。