File tree Expand file tree Collapse file tree 3 files changed +71
-1
lines changed Expand file tree Collapse file tree 3 files changed +71
-1
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * @author : Chisimdi Ezeanieto
3+ * @date : 29/03/2023
4+ *
5+ * @param {string } s
6+ * @return {number }
7+ */
8+ const symbolValue = {
9+ "I" : 1 ,
10+ "V" : 5 ,
11+ "X" : 10 ,
12+ "L" : 50 ,
13+ "C" : 100 ,
14+ "D" : 500 ,
15+ "M" : 1000
16+ } ;
17+ const romanToInt = function ( s ) {
18+ // Convert each roman numeral to number and place each in an array.
19+ const numbers = s . split ( '' ) . reduce ( ( curr , value ) => {
20+ curr . push ( symbolValue [ value ] ) ;
21+ return curr ;
22+ } , [ ] ) ;
23+ // Loop through the array and check if the current roman is greater than the next
24+ let total = 0 ;
25+ let i = 0 ;
26+
27+ while ( i < numbers . length ) {
28+ if ( i < numbers . length - 1 ) {
29+ if ( numbers [ i ] > numbers [ i + 1 ] ) {
30+ total += numbers [ i ] ;
31+ i ++ ;
32+ } else if ( numbers [ i ] === numbers [ i + 1 ] ) {
33+ total += ( numbers [ i + 1 ] + numbers [ i ] ) ;
34+ i += 2 ;
35+ } else {
36+ total += ( numbers [ i + 1 ] - numbers [ i ] ) ;
37+ i += 2 ;
38+ }
39+ } else {
40+ total += numbers [ i ] ;
41+ i ++ ;
42+ }
43+ }
44+ return total ;
45+ } ;
46+
47+ module . exports = romanToInt ;
Original file line number Diff line number Diff line change 1+ /*
2+ * @author : Chisimdi Damian Ezeanieto
3+ * @date : 16/03/2023
4+ */
5+ const romanToInt = require ( './index' ) ;
6+
7+ describe ( 'Phone key pad match' , ( ) => {
8+ test ( 'romanToInt function is defined' , ( ) => {
9+ expect ( typeof romanToInt ) . toEqual ( 'function' ) ;
10+ } ) ;
11+ test ( 'Convert roman to int for "I" === 1' , ( ) => {
12+ expect ( romanToInt ( 'I' ) ) . toEqual ( 1 ) ;
13+ } ) ;
14+ test ( 'Convert roman to int for "III" === 3' , ( ) => {
15+ expect ( romanToInt ( 'III' ) ) . toEqual ( 3 ) ;
16+ } ) ;
17+ test ( 'Convert roman to int for "LVIII" === 58' , ( ) => {
18+ expect ( romanToInt ( "LVIII" ) ) . toEqual ( 58 ) ;
19+ } ) ;
20+ test ( 'Convert roman to int for "MCMXCIV" === 1994' , ( ) => {
21+ expect ( romanToInt ( "MCMXCIV" ) ) . toEqual ( 1994 ) ;
22+ } ) ;
23+ } ) ;
Original file line number Diff line number Diff line change @@ -23,7 +23,7 @@ const reverseString = (str) => {
2323 // Switch positions as I loop through the string.
2424 // Big(O) = log N
2525 for ( let i = 0 ; i < Math . floor ( str . length / 2 ) ; i ++ ) {
26- [ str [ i ] , str [ str . length - 1 - i ] ] = [ str [ str . length - 1 - i ] , str [ i ] ] ;
26+ [ str [ i ] , str [ str . length - 1 - i ] ] = [ str [ str . length - 1 - i ] , str [ i ] ] ;
2727 }
2828 return str . join ( '' ) ;
2929} ;
You can’t perform that action at this time.
0 commit comments