Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 3792f19

Browse filesBrowse files
authored
adding comments 13. Roman to Integer.js
1 parent a33e3fe commit 3792f19
Copy full SHA for 3792f19

File tree

1 file changed

+26
-2
lines changed
Filter options

1 file changed

+26
-2
lines changed

‎11-20/13. Roman to Integer.js

Copy file name to clipboard
+26-2Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,56 @@
11
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
35
let [obj1,obj2] = [{"I":2,"X":20},{"I":2,"X":20,"C":200}]
6+
// loop the roman no. string
47
for(let i = 0 ; i < s.length;i++){
8+
// if I add 1 to ans
59
if( s[i] == "I" ){ans += 1}
10+
// if V add 5 to ans
611
if( s[i] == "V" ){
712
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
816
if( s[i-1] == "I" ) {ans -= 2}
917
}
18+
// if X add 10 to ans
1019
if( s[i] == "X" ){
1120
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
1224
if( s[i-1] == "I" ) {ans -= 2}
1325
}
26+
// if L add 50 to ans
1427
if( s[i] == "L" ){
1528
ans += 50
29+
// we check the for any IL or XL combination
30+
// subtract the value accordingly
1631
if(obj1[s[i-1]]){ans -= obj1[s[i-1]]}
1732
}
33+
// if C add 100 to ans
1834
if( s[i] == "C" ){
1935
ans += 100
36+
// we check the for any IC or XC combination
37+
// subtract the value accordingly
2038
if(obj1[s[i-1]]){ans -= obj1[s[i-1]]}
2139
}
40+
// if D add 500 to ans
2241
if( s[i] == "D" ){
2342
ans += 500
43+
// we check the for any ID or XD or CD combination
44+
// subtract the value accordingly
2445
if(obj2[s[i-1]]){ans -= obj2[s[i-1]]}
2546
}
47+
// if M add 1000 to ans
2648
if( s[i] == "M"){
2749
ans += 1000
50+
// we check the for any IM or XM or CM combination
51+
// subtract the value accordingly
2852
if(obj2[s[i-1]]){ans -= obj2[s[i-1]]}
2953
}
3054
}
3155
return ans
32-
};
56+
};

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.