문제

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol Value I V X L C D M
  1 5 10 50 100 500 1000

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • 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.

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

 

풀이

구현 문제이다.

나올 수 있는 모든 경우를 unordered_map에 저장하여 로마자를 key로 해당하는 숫자를 value로 저장한다.

그 후, string을 순회하면서 숫자를 모두 더한다.

 

코드

class Solution {
public:
    int romanToInt(string s) {
        unordered_map<string,int> a;
        a["I"]=1, a["V"]=5, a["X"]=10, a["L"]=50;
        a["C"]=100, a["D"]=500, a["M"]=1000;
        a["IV"]=4, a["IX"]=9, a["XL"]=40;
        a["XC"]=90, a["CD"]=400, a["CM"]=900;
        
        int ans=0;
        for(int i=0;i<s.length();i++)
        {
            string two=s.substr(i,2);
            if(a.find(two) != a.end()) ans += a[two], i++;
            else ans += a[s.substr(i,1)];
        }
        return ans;
    }
};

'PS > leetcode' 카테고리의 다른 글

[leetcode] 15. 3Sum  (0) 2019.04.29
[leetcode] 14. Longest Common Prefix  (0) 2019.04.29
[leetcode] 12. Integer to Roman  (0) 2019.04.29
[leetcode] 11. Container With Most Water  (0) 2019.04.29
[leetcode] 10. Regular Expression Matching  (0) 2019.04.28

+ Recent posts