|
1 | 1 | var romanToInt = function(s) {
|
2 |
| -let ans = 0; |
| 2 | +let ans = 0; // ans stores value of roman no. |
| 3 | +// objects are used to refracter the code |
| 4 | +// reducing multiple ifs to single if |
3 | 5 | let [obj1,obj2] = [{"I":2,"X":20},{"I":2,"X":20,"C":200}]
|
| 6 | +// loop the roman no. string |
4 | 7 | for(let i = 0 ; i < s.length;i++){
|
| 8 | + // if I add 1 to ans |
5 | 9 | if( s[i] == "I" ){ans += 1}
|
| 10 | + // if V add 5 to ans |
6 | 11 | if( s[i] == "V" ){
|
7 | 12 | ans += 5
|
| 13 | + // if we have IV that means 4 but |
| 14 | + // we have already add 1 in previous iteration |
| 15 | + // we need to subtract 2 to make it 4 |
8 | 16 | if( s[i-1] == "I" ) {ans -= 2}
|
9 | 17 | }
|
| 18 | + // if X add 10 to ans |
10 | 19 | if( s[i] == "X" ){
|
11 | 20 | ans += 10
|
| 21 | + // if we have IX that means 9 but |
| 22 | + // we have already add 1 in previous iteration |
| 23 | + // we need to subtract 2 to make it 9 |
12 | 24 | if( s[i-1] == "I" ) {ans -= 2}
|
13 | 25 | }
|
| 26 | + // if L add 50 to ans |
14 | 27 | if( s[i] == "L" ){
|
15 | 28 | ans += 50
|
| 29 | + // we check the for any IL or XL combination |
| 30 | + // subtract the value accordingly |
16 | 31 | if(obj1[s[i-1]]){ans -= obj1[s[i-1]]}
|
17 | 32 | }
|
| 33 | + // if C add 100 to ans |
18 | 34 | if( s[i] == "C" ){
|
19 | 35 | ans += 100
|
| 36 | + // we check the for any IC or XC combination |
| 37 | + // subtract the value accordingly |
20 | 38 | if(obj1[s[i-1]]){ans -= obj1[s[i-1]]}
|
21 | 39 | }
|
| 40 | + // if D add 500 to ans |
22 | 41 | if( s[i] == "D" ){
|
23 | 42 | ans += 500
|
| 43 | + // we check the for any ID or XD or CD combination |
| 44 | + // subtract the value accordingly |
24 | 45 | if(obj2[s[i-1]]){ans -= obj2[s[i-1]]}
|
25 | 46 | }
|
| 47 | + // if M add 1000 to ans |
26 | 48 | if( s[i] == "M"){
|
27 | 49 | ans += 1000
|
| 50 | + // we check the for any IM or XM or CM combination |
| 51 | + // subtract the value accordingly |
28 | 52 | if(obj2[s[i-1]]){ans -= obj2[s[i-1]]}
|
29 | 53 | }
|
30 | 54 | }
|
31 | 55 | return ans
|
32 |
| -}; |
| 56 | +}; |
0 commit comments