LeetCode12: Integer to Roman

来源:互联网 发布:可免费下载音乐的软件 编辑:程序博客网 时间:2024/04/29 02:46

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.


public class Solution {    public String intToRoman(int num) {        // Start typing your Java solution below        // DO NOT write main() function        char[] romanC = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};        int[] base = {1000, 500, 100, 50, 10, 5, 1};        int i=0;        int count=0;        String romanStr="";        while(i<romanC.length){            if(num-base[i]>=0){                num-=base[i];                count++;            }            else{                String tmpStr="";                if(count==4){                    tmpStr += romanC[i];                    tmpStr += romanC[i-1];                    count=0;                }                else if(count>=5 && count<9){                    tmpStr += romanC[i-1];                    count-=5;                }                else if(count==9){                    tmpStr += romanC[i];                    tmpStr += romanC[i-2];                    count=0;                }                while(count>0){                    tmpStr+=romanC[i];                    count--;                }                romanStr += tmpStr;                i+=2;                count=0;            }        }        return romanStr;    }}


原创粉丝点击