阿拉伯数字转罗马数字

import java.util.ArrayList;

/**
 * 阿拉伯数字转为罗马数字 ( 0~3999 )
 * Created by chris on 2014/11/17.
 */
public class numbersToRomans {
    private final int JINZHI = 10;

    public String intToRoman(int num) {
        ArrayList<Integer> a = new ArrayList();
        StringBuffer sb = new StringBuffer();
        String []roman = {"","I","II","III","IV","V","VI","VII","VIII","IX"};
        String []roman2 = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
        String []roman3 = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};

        int count = 0;
        while (num  != 0){
            count++;
            a.add(num % JINZHI);
            num = num /JINZHI ;
        }

        for (int i = count ; i > 0 ; i--) {
            switch (i){
                case 1:
                    sb.append(roman[a.get(i-1)]);
                    break;
                case 2:
                    sb.append(roman2[a.get(i-1)]);
                    break;
                case 3:
                    sb.append(roman3[a.get(i-1)]);
                    break;
                case 4:
                    for (int j = 0;j < a.get(i-1);j++){
                        sb.append('M');
                    }
                    break;
            }
        }
        return sb.toString();

    }
/**
 * 精简版本by flytosky
 * */
    String intToRoman2(int num) {
        String M[] = {"", "M", "MM", "MMM"};
        String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
        String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
        String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
        return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
    }
}



罗马数字转阿拉伯数字

Tagged on: , ,

One thought on “阿拉伯数字转罗马数字

  1. Pingback: leetcode 罗马数字转阿拉伯数字 | Christopher

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>