-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegerToRoman.js
More file actions
36 lines (31 loc) · 872 Bytes
/
integerToRoman.js
File metadata and controls
36 lines (31 loc) · 872 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* LeetCode 12. Integer to Roman
* https://leetcode.com/problems/integer-to-roman/description/
*
* Seven different symbols represent Roman numerals:
* I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000
*
* Additionally, subtractive notation is used:
* IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, CM = 900
*
* Given an integer, convert it to a Roman numeral.
*
* Constraints: 1 <= num <= 3999
*/
const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
const symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
/**
* @param {number} num
* @return {string}
*/
function intToRoman(num) {
let result = "";
for (let i = 0; i < values.length; i++) {
while (num >= values[i]) {
result += symbols[i];
num -= values[i];
}
}
return result;
}
module.exports = { intToRoman };