EvanJames的专栏

Be Real. Be Yourself.

[LeetCode][Java] 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之间。


算法分析:

 参考了博客http://www.cnblogs.com/springfor/p/3886459.html


 * 对老中来说,不熟悉罗马数字的规律是个问题。其实就是那么几个符号,然后规律就是 1,4,5,9,10 然后每次十倍循环。
 * 算法就是给一个数,大于1000的时候就写上一个M, 还大于1000,再写一个M… 终于小于1000了,看看大于900不?,大于500不…如此类推。
 * 罗马数字为以下表示形式:
  I 1
  V 5
  X 10
  L 50
  C 100
  D 500
  M 1,000

AC代码:

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


阅读更多
版权声明:本文为博主原创文章,转载注明出处 https://blog.csdn.net/Evan123mg/article/details/46813165
个人分类: LeetCode
上一篇[LeetCode][Java] Container With Most Water
下一篇[LeetCode][Java] Roman to Integer
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭