Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d5d40a3

Browse files
committedSep 24, 2021
Add solution #12
1 parent a360b2d commit d5d40a3

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
7|[Reverse Integer](./0007-reverse-integer.js)|Easy|
1414
8|[String to Integer (atoi)](./0008-string-to-integer-atoi.js)|Medium|
1515
10|[Regular Expression Matching](./0010-regular-expression-matching.js)|Hard|
16+
12|[Integer to Roman](./0012-integer-to-roman.js)|Medium|
1617
14|[Longest Common Prefix](./0014-longest-common-prefix.js)|Easy|
1718
17|[Letter Combinations of a Phone Number](./0017-letter-combinations-of-a-phone-number.js)|Medium|
1819
27|[Remove Element](./0027-remove-element.js)|Easy|

‎solutions/0012-integer-to-roman.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 12. Integer to Roman
3+
* https://leetcode.com/problems/integer-to-roman/
4+
* Difficulty: Medium
5+
*
6+
* Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`.
7+
*
8+
* Symbol Value
9+
* I 1
10+
* V 5
11+
* X 10
12+
* L 50
13+
* C 100
14+
* D 500
15+
* M 1000
16+
*
17+
* For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written
18+
* as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`.
19+
*
20+
* Roman numerals are usually written largest to smallest from left to right. However, the numeral for
21+
* four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five
22+
* we subtract it making four. The same principle applies to the number nine, which is written as `IX`.
23+
* There are six instances where subtraction is used:
24+
*
25+
* - `I` can be placed before `V (5)` and `X (10)` to make 4 and 9.
26+
* - `X` can be placed before `L (50)` and `C (100)` to make 40 and 90.
27+
* - `C` can be placed before `D (500)` and `M (1000)` to make 400 and 900.
28+
*
29+
* Given an integer, convert it to a roman numeral.
30+
*/
31+
32+
/**
33+
* @param {number} num
34+
* @return {string}
35+
*/
36+
var intToRoman = function(num) {
37+
const map = { M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90, L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1 };
38+
39+
return Object.entries(map).reduce((result, [letter, n]) => {
40+
result += letter.repeat(Math.floor(num / n));
41+
num %= n;
42+
return result;
43+
}, '');
44+
};

0 commit comments

Comments
 (0)
Please sign in to comment.