#LeetCode:13. Roman to Integer

灆洢 2018-10-04 09:03:50

比對加總即可。唯一的例外就是當下該位的數值比右邊那位的數值小的時候要用減的,也就是 IVIX ……等等這些狀況。

C++(48ms)

/*******************************************************/
/* LeetCode 13. Roman to Integer                       */
/* Author: Maplewing [at] knightzone.studio            */
/* Version: 2018/10/04                                 */
/*******************************************************/
#include <map>

class Solution {
private:
  const map<char, int> TABLE = { 
    {'I', 1}, {'V', 5}, {'X', 10},
    {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}
  };

public:
  int romanToInt(string s) {
    int value = TABLE.at(s[s.length()-1]);
    for(int i = s.length() - 2 ; i >= 0 ; --i){
      if(TABLE.at(s[i]) < TABLE.at(s[i+1])){
        value -= TABLE.at(s[i]);
        continue;
      }

      value += TABLE.at(s[i]);
    }

    return value;
  }
};

在〈“#LeetCode:13. Roman to Integer”〉中有 1 則留言

#生活趣事:[18.10.01~18.10.07] -開始失落的一週 - 翼世界夢想領域翼世界夢想領域 發表迴響 取消回覆

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料