-
Notifications
You must be signed in to change notification settings - Fork 181
/
Copy pathDecimaltoRoman.js
53 lines (45 loc) · 1.12 KB
/
DecimaltoRoman.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// javascript code implementation
function integerToRoman(num) {
let roman = new Map(); // move outside
roman.set(1, 'I');
roman.set(5, 'V');
roman.set(10, 'X');
roman.set(50, 'L');
roman.set(100, 'C');
roman.set(500, 'D');
roman.set(1000, 'M');
roman.set(5000, 'G');
roman.set(10000, 'H');
let tmp = Array.from(String(num));
let numDigits = tmp.length;
let res = [];
for(let i=0;i<numDigits;++i) {
let src = tmp[i]; // orig
let number = (src.charCodeAt(0) - 48); // convert to integer
let place = (numDigits-1)-i;
let absolute = Math.pow(10, place);
if (number == 9) {
res.push(roman.get(absolute));
res.push(roman.get((number+1) * absolute));
} else
if (number >= 5) {
res.push(roman.get(5*absolute));
let cnt = number-5;
while(cnt--) res.push(roman.get(absolute));
}
else{
if (number >= 4) {
res.push(roman.get(absolute));
res.push(roman.get(5*absolute));
}
else {
let cnt = number;
while(cnt--) res.push(roman.get(absolute));
}
}
}
return res;
}
let ans = integerToRoman(3549).join('');
console.log(ans);
// This code is contributed by Nidhi goel.