문제
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 an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
풀이
구현 문제다. 잘 찍히기만 하면 되기 때문에, 다양한 방법이 있을 수 있다.
본인은 아래와 같이 roman함수를 만들어서 구현하였다.
코드
class Solution {
private:
string roman(int num, string one, string five, string ten)
{
if(num==9) return one+ten;
if(num==4) return one+five;
string ret;
if(num>=5)ret+=five;
for(int i=0;i<num%5;i++)ret+=one;
return ret;
}
public:
string intToRoman(int num) {
int tho = num/1000;
int hun = num/100%10;
int ten = num/10%10;
int one = num%10;
string ret;
return roman(tho,"M","x","x") + roman(hun,"C","D","M")
+ roman(ten,"X","L","C") + roman(one,"I","V","X");
}
};
'PS > leetcode' 카테고리의 다른 글
[leetcode] 14. Longest Common Prefix (0) | 2019.04.29 |
---|---|
[leetcode] 13. Roman to Integer (0) | 2019.04.29 |
[leetcode] 11. Container With Most Water (0) | 2019.04.29 |
[leetcode] 10. Regular Expression Matching (0) | 2019.04.28 |
[leetcode] 9. Palindrome Number (0) | 2019.04.28 |