【LeetCode & 劍指offer刷題】發散思維題8:Roman to Integer
阿新 • • 發佈:2019-01-06
【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)
Roman to Integer
Roman numerals are represented by seven different symbols: I , V , X , L , C , D and- I can be placed before V (5) and X (10) to make 4 and 9.
- X can be placed before L (50) and C (100) to make 40 and 90.
- C can be placed before D (500) and M (1000) to make 400 and 900.
C++ //問題:羅馬數字轉成整數 /* Roman numerals are usually written largest to smallest from left to right. 一般從大到小寫,如果從小到大寫為減法,如IV(4) IX(9) */ #include <unordered_map> #include <string> class Solution { public : int romanToInt ( string s ) { unordered_map < char , int > map = { { 'I' , 1 }, { 'V' , 5 }, { 'X' , 10 }, { 'L' , 50 }, { 'C' , 100 }, { 'D' , 500 }, { 'M' , 1000 } }; int sum = map [ s . back ()]; //字串末尾字元 for ( int i = s . size ()- 2 ; i >= 0 ; i --) //從後往前掃描 { if ( map [ s [ i ]] < map [ s [ i + 1 ]]) sum -= map [ s [ i ]]; //當前字元比後面字元對應數值小時,用減法 else sum += map [ s [ i ]]; } return sum ; } };