12.整数转罗马数字
方法:模拟
分析罗马数字的规则是:对于罗马数字从左到右的每一位,选择尽可能大的符号值
根据罗马数字的唯一表示法,为了表示一个给定的整数num,寻找不超过num的最大符号值,将num减去该符号值,然后继续寻找不超过num的最大符号值,将该符号拼接再上一个找到的符号之后,循环直至num为0,最后得到的字符串即为num的罗马数字表示
class Solution {int[] values ={1000,900,500,400,100,90,50,40,10,9,5,4,1};String[] symbols = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};public String intToRoman(int num) {StringBuffer s = new StringBuffer();for(int i = 0;i < values.length;i++){int value = values[i];while(num >= value){num -= value;s.append(symbols[i]);}if(num == 0){break;}}return s.toString();}
}