LeetCodeブラシ問題day 012(Jieky)


LeetCode第12題
/*
Roman numerals are represented by seven different symbols: I(1), V(5), X(10), L(50), C(100), D(500) and M(1000).
For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII which is simply X + II The number twenty seven is written as XXII, which is XX +V+II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine which is written as IX. There are six instances where subtraction is used:
	can be placed before V (5) and X (10) to make 4 and 9.
	can be placed before L (50) and C (100) to make 40 and 90
	can be placed before D (500) and M(1000) to make 400 and 900
Given an integer, convert it to a roman numeral. 
Input is guaranteed to be within the range from 1 to 3999
*/
public class IntegerToRoman{
     
	public static void main(String[] args){
     
		IntegerToRoman itr = new IntegerToRoman();
		String result = itr.intToRoman02(14);
		System.out.println(result);
	}
	public String intToRoman02(int num) {
     
		if (num < 1 || num >3999) return null;
		
		String ret = "";
		int pos = 3;
		while(num > 0){
     
			ret += getRoman(num/(int)Math.pow(10,pos),pos);
			num = num%(int)Math.pow(10,pos);
			pos--;
		}
		return ret;
	}
	// 0  1  2  3 
	public String getRoman(int num,int pos) {
     
		String[] roman = {
     "I","V","X","L","C","D","M"};
		
		String ret = "";
		if(num < 4){
     
			int count = num;
			while(count > 0){
     
				ret += roman[pos*2];
				count--;
			}
		}else if(num == 4){
     
			ret = roman[pos*2] + roman[pos*2 + 1];
		}else if(num > 4 && num < 9){
     
			int count = num;
			ret = roman[pos*2 + 1];
			while(count > 5){
     
				ret += roman[pos*2]; 
				count--;
			}
		}else if(num == 9){
     
			ret = roman[pos*2] + roman[pos*2 + 2];
		}
		return ret;
	}
	
	//     
	public String intToRoman01(int num) {
     
		if (num < 1 || num >3999) return null;
		
		String M[] = {
     "", "M", "MM", "MMM"};//0,1000,2000,3000
		String C[] = {
     "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};//0,100,200,300...
		String X[] = {
     "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};//0,10,20,30...
		String I[] = {
     "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};//0,1,2,3...
		return M[num/1000] + C[(num%1000)/100]+ X[(num%100)/10] + I[num%10];
	}

}