Converting Decimal Number lying between 1 to 3999 to Roman Numerals
Examples: Input : 9Output : IXInput : 40Output : XLInput : 1904Output : MCMIV Following is the list of Roman symbols which include subtractive cases also: SYMBOL VALUEI 1IV 4V 5IX 9X 10XL 40L 50XC 90C 100CD 400D 500CM 900 M 1000 The plan is to separately convert the tens, hundreds, thousands of sites of the specified number. There is no matching Roman numeral symbol if the digit is zero. Because these digits use subtractive notation, the conversion of digits 4’s and 9’s is somewhat different from other digits. Method for Roman numeral conversion from decimal numberComparing provided number with base values in the sequence 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1, The first base value—largest base value—will be either exactly less or equal to the specified integer.Divide the number by its highest base value; the corresponding base symbol will be repeated quotient times; the residual will then be the number for next divisions and repetitions. The cycle will be continued until the count runs zero. Example to demonstrate above algorithm: Convert 3549 to its Roman Numerals Output: MMMDXLIX Explanation: First step: First number = 3549Since 3549 > 1000; first base value will be 1000 initially.Get 3549/1000 divided. Remainder =549; quotient = 3. Three times will be the equivalent sign M repeated.We list the Result value in the second list.Now remainder is not equal to zero hence we call the method once more. Two steps Number now is 549; maximum base value will be 500; 1000 > 549 >= 500.Split 549/500. Remainder: 49; quotient: 1. Once, the matching symbol D will be repeated to stop the loop.We list the Result value in the second list.Now remainder is not equal to zero hence we call the method once more.The third step Number now is 49; maximum base value is 40; 50 > 49 >= 40.Sort 49/40. Quotient is one; remainder is nine. Once, the matching symbol XL will be repeated to stop the loop.We list the Result value in the second list.Now remainder is not equal to zero hence we call the method once more.Step Four Now, number is 9.List l contains number 9; so, we straight get the value from dictionary dict and set Remainder=0 and finish the loop.Remainder= 0. We shall not call the method once more since the related symbol IX will be repeated once and the remaining value is 0.Step five At last, we align with the second list values.The result came MMMDXLIX.The above method is applied following here: C++ Java Python C# Output MMMDXLIX Time Complexity: O(N), where N is the length of ans string that stores the conversion.Auxiliary Space: O(N)
Converting Decimal Number lying between 1 to 3999 to Roman Numerals Read More »