Skip to content

Latest commit

 

History

History
30 lines (21 loc) · 1.01 KB

12. Integer to Roman.md

File metadata and controls

30 lines (21 loc) · 1.01 KB

12. Integer to Roman

Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
public String intToRoman(int num) {
    	//先去维基上了解下罗马数字:https://en.wikipedia.org/wiki/Roman_numerals
    	
    	String roman = "";
    	//这些数字需要手动写,因为40, 50,90, 400, 500,有特定表示法。写loop似乎不值当。
    	//数列首位空格,这样刚好和数列index对应。
    	String [] ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
    	String [] tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
    	String [] hundreds = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
    	String [] thousands = {"", "M", "MM", "MMM"};

    	//需要求得的是每个位置的个位数,%10来保证。
    	roman += thousands [num/1000];
  
    	roman += hundreds [num/100%10];

    	roman += tens [num/10%10];

    	roman += ones[num/1%10]; 
    
    	return roman;
    }