当前位置:网站首页>Leetcode topic resolution integer to Roman

Leetcode topic resolution integer to Roman

2022-06-23 06:02:00 ruochen

Given an integer, convert it to a roman numeral.

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

  1. Write the same numbers together , The number represented is equal to the sum of these numbers , Such as :Ⅲ = 3;
  2. The small number is to the right of the big number , The number represented is equal to the sum of these numbers , Such as :Ⅷ = 8;Ⅻ = 12;
  3. Small numbers ,( Be limited to Ⅰ、X and C) To the left of the big numbers , The number represented is equal to the number obtained by subtracting the decimal from the large number , Such as :Ⅳ= 4;Ⅸ= 9;
  4. In normal use , Consecutive numbers should not be repeated more than three times .( Four o'clock on the dial “IIII” exception );
  5. Draw a horizontal line over a number , Indicates that the number is enlarged 1000 times .
    public String intToRoman(int num) {
        final int[] values = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5,
                4, 1 };
        final String[] symbol = { "M", "CM", "D", "CD", "C", "XC", "L", "XL",
                "X", "IX", "V", "IV", "I" };
        StringBuilder result = new StringBuilder();
        for (int i = 0; num > 0; i++) {
            int count = num / values[i];
            num %= values[i];
            for (; count > 0; count--) {
                result.append(symbol[i]);
            }
        }
        return new String(result);
    }
原网站

版权声明
本文为[ruochen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201151252028591.html