Roman to Integer - LeetCode
生活随笔
收集整理的這篇文章主要介紹了
Roman to Integer - LeetCode
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
目錄
- 題目鏈接
- 注意點
- 解法
- 小結(jié)
題目鏈接
Roman to Integer - LeetCode
注意點
- 大的數(shù)字在小的數(shù)字左邊是正常情況,要考慮的是小的數(shù)字在大的數(shù)字右邊的那8種情況
解法
解法一:從右至左,對于出現(xiàn)的每個字符逐個判斷,累加。時間復(fù)雜度為O(n)
class Solution { public:int romanToInt(string s) {int i,n = s.size(),anw = 0;for(i = n-1;i >= 0;i--){if(s[i] == 'M'){if(s[i-1] == 'C'){anw += 900;i--;}else{anw += 1000;}}else if(s[i] == 'D'){if(s[i-1] == 'C'){anw += 400;i--;}else{anw += 500;}}else if(s[i] == 'C'){if(s[i-1] == 'X'){anw += 90;i--;}else{anw += 100;}}else if(s[i] == 'L'){if(s[i-1] == 'X'){anw += 40;i--;}else{anw += 50;}}else if(s[i] == 'X'){if(s[i-1] == 'I'){anw += 9;i--;}else{anw += 10;}}else if(s[i] == 'V'){if(s[i-1] == 'I'){anw += 4;i--;}else{anw += 5;}}else if(s[i] == 'I'){anw += 1;}//printf("%d\n",anw);}return anw;} };解法二:從左至右。如果之前的數(shù)字小于當(dāng)前的就減去之前的數(shù)字,否則就加上。最后一個字符無論如何都加上。時間復(fù)雜度O(n)
class Solution { public:int romanToInt(string s) {map<char,int> m;m['I'] = 1;m['V'] = 5;m['X'] = 10;m['L'] = 50;m['C'] = 100;m['D'] = 500;m['M'] = 1000;int i,n = s.size(),anw = 0;int before = m[s[0]],now = 0;for(i = 1;i < n;i++){now = m[s[i]];if(before < now){anw -= before;}else{anw += before;}before = now;}anw += before;return anw;} };小結(jié)
- 理解了羅馬數(shù)字的原理這題就不難
轉(zhuǎn)載于:https://www.cnblogs.com/multhree/p/10320230.html
總結(jié)
以上是生活随笔為你收集整理的Roman to Integer - LeetCode的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: svn学习笔记(一)
- 下一篇: win10系统盘u盘怎么做系统 制作Wi