Question
Given an integer, write a function to return its roman numeral representation.
eg.
1 2 3 |
integerToRoman(1) = "I" integerToRoman(4) = "IV" integerToRoman(49) = "XLIX" |
Once you think that you’ve solved the problem, click below to see the solution.
As always, remember that practicing coding interview questions is as much about how you practice as the question itself. Make sure that you give the question a solid go before skipping to the solution. Ideally if you have time, write out the solution first by hand and then only type it into your computer to verify your work once you've verified it manually. To learn more about how to practice, check out this blog post.
Solution
How was that problem? You can check out the solution in the video below.
Here is the source code for the solution shown in the video (Github):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// Parallel arrays of numerals in descending order and their values. We // include any pairs of numerals where a smaller numeral is subtracted from // a larger numeral private static final String[] numerals = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; private static final int[] values = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; public static String integerToRoman(int value) { // We are only considering the range for standard roman numerals if (value > 3999 || value < 1) throw new IllegalArgumentException(); StringBuilder numeral = new StringBuilder(); int i = 0; // Greedily append the largest numeral possible until the value is 0 while (value > 0) { if (value - values[i] >= 0) { numeral.append(numerals[i]); value -= values[i]; } else { i++; } } return numeral.toString(); } |
Did you get the right answer to this coding interview question? Please share your thoughts in the comments below.