r/csinterviewproblems • u/qibag • Dec 18 '15
Convert an integer < 4000 into a roman numeral.
input:
78output:
LXXVIIISource: Google phone interview
25
Upvotes
r/csinterviewproblems • u/qibag • Dec 18 '15
input:
78output:
LXXVIIISource: Google phone interview
8
u/uppstoppadElefant Dec 18 '15 edited Dec 18 '15
Python:
3
u/Waifu4Laifu Dec 18 '15 edited Dec 18 '15
edit: I forgot how roman numerals work lol (eg: 45 = XLV), my solution doesn't account for those. this can be fixed by using same method /u/uppstoppadElefant used, adding in the IV, IX, etc into the character array and the corresponding number in the divider array.
I took a crack at it in Javascript, here is what I came up with:
I use 2 arrays to keep the roman numeral characters as well as their values. I use a for loop to iterate through the length of the list (the total possible numerals) and divide the value to get the number of times that numeral should be printed.
If the division has a result, then we want to print out the current character as many times as the number can be divided by the value of that letter.
Then we decrease the value by the ones we just checked. If none were found to exist, we can ignore it and go to next character.
Example of input: 2341
Each time a letter exists, we append them the output string, and return/log that after the loop ends to get the roman numeral representation.
1
u/vicky002 Dec 19 '15 edited Dec 19 '15
1
u/towerofterror Dec 21 '15
So I started working on this before seeing everybody's answers, and very quickly faced the problem that 40 is XL, not XXXX.
After a lot of thinking I found a complicated if statement that made 40=>XL work. Then I saw all of the solutions below, and felt very dumb. Anyway, here's my solution in python:
1
u/sje46 Dec 21 '15
Would love if someone would comment on this:
1
u/TimPowerGamer Feb 05 '16
I took a stab at this in C#.
-1
u/CodeTinkerer Dec 18 '15
It's interesting this is a question (I don't think it should be). I think it used to be much more common to teach Roman numerals (not sure why), but if a person doesn't know how it works, then the person is having to wrestle with two problems.