Converting integers to roman numerals

前端 未结 29 2404
走了就别回头了
走了就别回头了 2020-12-02 09:16

I\'m trying to write a function that converts numbers to roman numerals. This is my code so far; however, it only works with numbers that are less than 400. Is there a quick

29条回答
  •  情深已故
    2020-12-02 09:57

    public static String convert(int num)
    {
        String[] charsArray  = {"I", "IV", "V", "IX", "X", "XL", "L", "XC","C","CD","D","CM","M" };
        int[] charValuesArray = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
    
        String resultString = "";
        int temp = num;
        int [] resultValues = new int[13];
        // Generate an array which "char" occurances count
        for(int i = 12 ; i >= 0 ; i--)
        {
            if((temp / charValuesArray[i]) > 0)
            {
                resultValues[i] = temp/charValuesArray[i];
                temp = temp % charValuesArray[i];
            }
        }
        // Print them if not occured do not print
        for(int j = 12 ; j >= 0 ; j--)
        {
            for(int k = 0 ; k < resultValues[j]; k++)
            {
                resultString+= charsArray[j];
            }
        }
        return resultString;
    
    }
    

提交回复
热议问题