【LeetCode】12. Integer to Roman 整型数转罗马数

题目:

  Given an integer, convert it to a roman numeral.

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

思路:

  主要是了解罗马数和阿拉伯数字的对应关系,如下表:

      

由这个表基本上可以将1-3999范围的阿拉伯数字换成罗马数字。在处理阿拉伯数字时从高位开始匹配,将每个位的值找出对应罗马数字,串成字符串即可。

public class Solution {
    public String intToRoman(int num) {
        int[] val={1000,900,500,400,100,90,50,40,10,9,5,4,1};
        String[] sym={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        
        String rom="";
        for(int i=0;i<val.length;i++){
            while(num>=val[i]){
                rom+=sym[i];
                num-=val[i];
            }
        }
        return rom;
    }
}

  

原文地址:https://www.cnblogs.com/zhstudy/p/6013924.html