N
(Leet Code c++)Integer to Roman 본문
12. Integer to Roman
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000
For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 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 an integer, convert it to a roman numeral.
Example 1:
Input: num = 3 Output: "III"
Example 2:
Input: num = 4 Output: "IV"
Example 3:
Input: num = 9 Output: "IX"
Example 4:
Input: num = 58 Output: "LVIII" Explanation: L = 50, V = 5, III = 3.
Example 5:
Input: num = 1994 Output: "MCMXCIV" Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
- 1 <= num <= 3999
int로 주어진 숫자를 roman 형태로 바꾸는 문제.
map을 활용하였다.
우선 keys 벡터에 roman에 해당하는 숫자를 모두 저장했다.
또한, map에도 keys에 알맞는 문자열을 저장했다.
while문으로 num > 0일 때까지 반복.
for문을 통해 현재 num의 범위를 알아내도록 한다.
현재 key 값보다 크거나 같고, 다음 key 값보다 작으면 해당 문자열을 answer에 저장한 후, 해당 키 값을 num에서 뺀다.
만약 num이 1000보다 높다면 for문을 모두 돌았다는 뜻이 된다.(break 되지 않았다!)
그렇다면 무조건 "M"을 추가한 후, num -= 1000을 해주어 계속 진행하면 된다.
class Solution {
public:
string intToRoman(int num) {
map<int, string> m;
string answer = "";
vector<int> keys = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
m[1] = "I";
m[4] = "IV";
m[5] = "V";
m[9] = "IX";
m[10] = "X";
m[40] = "XL";
m[50] = "L";
m[90] = "XC";
m[100] = "C";
m[400] = "CD";
m[500] = "D";
m[900] = "CM";
m[1000] = "M";
while(num > 0){
bool check = false;
for(int i = 0; i < keys.size(); i++){
if(i + 1 < keys.size() && num >= keys[i] && num < keys[i + 1]){
answer += m[keys[i]];
num -= keys[i];
check = true;
break;
}
}
if(!check){
answer += "M";
num -= 1000;
}
}
return answer;
}
};
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code c++)Excel Sheet Column Title (0) | 2021.07.20 |
---|---|
(Leet Code c++)Two Sum(2) - Input array is sorted (0) | 2021.07.20 |
(Leet Code c++)Intersection of Two Linked Lists (0) | 2021.07.19 |
(Leet Code c++)Min Stack (0) | 2021.07.19 |
(Leet Code c++)Binary Tree Postorder Traversal (0) | 2021.07.19 |