Leetcode 12. Integer to Roman
Description:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
Thinking:
Since the input is between 1 to 3999. We can solve the problem by digit. And we need to have a 4 String arrays, which is for unit, decade, hundreds and thousands.
Steps:
- Check whether input is valid.
- Get each digit of the integer and look up the Roman numeral in the corresponding String array.
- Use StringBuilder to build the Roman String.
Code:
public class Solution {
public String intToRoman(int num) {
if(num <=0 || num > 3999) return new String();
StringBuilder result = new StringBuilder();
String[] unit = {"","I","II","III","IV","V","VI","VII","VIII","IX"};
String[] decade = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
String[] hundred = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
String[] thousand = {"", "M","MM","MMM"};
result.append(thousand[num/1000]);
num = num %1000;
result.append(hundred[num/100]);
num = num%100;
result.append(decade[num/10]);
num = num%10;
result.append(unit[num]);
return result.toString();
}
}
Conclusion:
The problem becomes quite easy if we can think out that use 4 String arrays to store the information Roman numeral. This method is used for that cases number is not too big so that we can enumerate them.