问题:
解:
package com.example.demo; public class Test12 { private static final int[] values = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; private static final String[] symbols = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; /** * 将整数转为罗马数字 * 定义两个数组,一个数组列出所有可能出现的罗马数字的情况, * 另一个列出其对应的整数 * * @param num * @return */ public String intToRoman(int num) { StringBuffer sb = new StringBuffer(); int index = 0; while (num > 0) { int count = num / values[index]; for (int i = 0; i < count; i++) { sb.append(symbols[index]); // 将计算过的值-去(将算过的值去掉) num -= values[index]; } index++; } return sb.toString(); } public static void main(String[] args) { Test12 t = new Test12(); String s = t.intToRoman(1994); System.out.println(s); } }